/**
 * 字牌房间显示
 * Created by duwei on 2019/2/14.
 */
(function (exports) {
    exports.ZiPaiRoom = cc.Layer.extend({
        _ccsFileName: zipai.res.ZiPaiRoom_json,
        /**
         * 房间数据管理器
         */
        zipaiManager: null,

        /**
         * 移动牌相关
         */
        CHUPAI_HEIGHT: 480,
        MAXROW: 3,
        movecard: null,
        movecardTmp: null,
        positionBak: null,
        zorderBak: null,
        movetoxy: null,
        movetoxybak: null,
        movexy: null,
        cardsXYBak: [],
        //移动的牌
        movetocardArr: [],
        movetocardPosArr: [],
        isBeginTouch: false,

        isTurnOut: false,
        isTurnIn: false,

        outCardRow: null,
        outCardColumn: null,

        isBaiPai:true,
        /**
         * 更新函数
         * @private
         */
        update: function (dt) {
            if (!this._time)
                this._time = 0;
            this._time += dt;
            if (this._time >= 1) {
                if (this.PlayerInfoNode) {
                    for (var i = 0; i < zipai.curMaxPlayerNum; i++) {
                        var infoNode = this.$('info' + i, this.PlayerInfoNode);
                        if (infoNode) {
                            var time = infoNode.getChildByName('offline').getChildByName('time');
                            this.setOfflineTime(time);
                        }
                    }
                }


                this._time -= 1;
            }
        },
        setOfflineTime: function (node) {
            if (node) {
                if (_.isUndefined(node.timeNum)) {
                    node.timeNum = 0;
                } else {
                    node.timeNum++;
                }
                node.setString(secondToTime(node.timeNum));
            }
        },
        /**
         * 初始化时间监听
         */
        initEvent: function () {
            eventManager.addListener(ZiPaiEvent.UpPlayerPos, this.setUpPlayers.bind(this), this);
            eventManager.addListener(ZiPaiEvent.PlayersStatus, this.setPlayersStatus.bind(this), this);
            eventManager.addListener(ZiPaiEvent.UserDisconnect, this.setDisconnect.bind(this), this);
            eventManager.addListener(ZiPaiEvent.StatusChange, this.onStatusChange.bind(this), this);
            eventManager.addListener(ZiPaiEvent.GameStart, this.setUpGameStart.bind(this), this);
            eventManager.addListener(ZiPaiEvent.GameStartAnimation, this.setUpGameStartAnimation.bind(this), this);
            eventManager.addListener(ZiPaiEvent.CardDeal, this.setUpCards.bind(this), this);
            eventManager.addListener(ZiPaiEvent.ResetCards, this.resetCards.bind(this), this);
            eventManager.addListener(ZiPaiEvent.UpOtherCards, this.setUpOtherCards.bind(this), this);
            eventManager.addListener(ZiPaiEvent.BroadCast, this.setBroadCast.bind(this), this);
            eventManager.addListener(ZiPaiEvent.TurnOut, this.setTurnOut.bind(this), this);
            eventManager.addListener(ZiPaiEvent.TurnIn, this.setTurnIn.bind(this), this);
            eventManager.addListener(ZiPaiEvent.TishiList, this.setTishiList.bind(this), this);
            eventManager.addListener(ZiPaiEvent.TingCards, this.setTingPaiList.bind(this), this);
            eventManager.addListener(ZiPaiEvent.GameOver, this.setGameOver.bind(this), this);
            eventManager.addListener(ZiPaiEvent.JushouStatus, this.setJushouStatus.bind(this), this);
            eventManager.addListener(ZiPaiEvent.Baojing, this.setUpBaojing.bind(this), this);
            eventManager.addListener(ZiPaiEvent.QiePai, this.setUpQiePai.bind(this), this);
            eventManager.addListener(ZiPaiEvent.RoomResult, this.showRoomClean.bind(this), this);
            eventManager.addListener(ZiPaiEvent.QuickStart, this.onQuickStartGame.bind(this), this);
            eventManager.addListener(EventKey.ChangeTable, this.changeBg.bind(this), this);
            eventManager.addListener(EventKey.ChangePai, this.changePai.bind(this), this);
            eventManager.addListener(EventKey.ChangeBgm, this.changeBgm.bind(this), this);
            eventManager.addListener(EventKey.showhuxi, this.changeHuXi.bind(this), this);
            eventManager.addListener(EVENT_CLEAN_ROOM, this.beginReplay.bind(this), this);
            eventManager.addListener(EVENT_EATCARD, this.showReplayAction.bind(this), this);
            eventManager.addListener(EVENT_EATOVER, this.hideReplayAction.bind(this), this);
        },
        /**
         * 更新状态
         */
        onStatusChange: function () {
            this.txtRound.setString(this.zipaiManager.CurRound + '/' + this.zipaiManager.ZongRound);
        },
        onQuickStartGame: function () {
            var self = this;
            self.initPlayerInfoNode();
            self.setUpPlayers();
        },
        createQuickStart: function () {
            var self = this;
            self.QuickOption = [
                {key: 'PlayerCount', value: 2, deleteStr: ['三人玩'], addStr: ['二人玩']},
                {key: 'QuickStart', deleteStr: ['立即开局']},
                {key: 'Denghu', deleteStr: ['等胡']}
            ];
        },
        getQuickStartOption: function () {
            var self = this;
            self.createQuickStart();
            var Option = self.zipaiManager.Option;
            for (var i = 0; i < self.QuickOption.length; i++) {
                var OptionData = self.QuickOption[i];
                if (!_.isUndefined(OptionData.value)) {
                    Option[OptionData.key] = OptionData.value;
                } else if (!_.isUndefined(Option[OptionData.key])) {
                    delete Option[OptionData.key]
                }
            }
            var desp = Option['desp'].split(",");
            for (i = 0; i < self.QuickOption.length; i++) {
                OptionData = self.QuickOption[i];
                if (OptionData['deleteStr']) {
                    for (var k = 0; k < OptionData['deleteStr'].length; k++) {
                        var j = desp.indexOf(OptionData['deleteStr'][k]);
                        if (j < 0)
                            break;
                        desp.splice(j, 1);
                    }
                }
                if (OptionData['addStr']) {
                    for (k = 0; k < OptionData['addStr'].length; k++) {
                        desp.splice(j++, 0, OptionData['addStr'][k]);
                    }
                }
            }
            Option['desp'] = desp.join(',');
            Option['wanfadesc'] = desp.join(',');
            return JSON.stringify(Option);
        },
        initTouch: function () {
            var self = this;
            /**
             * 点击准备按钮
             */
            TouchUtil.setOnclickListener(self.$('FunctionBtn.bottomCenter.btn_zhunbei'), function (node) {
                network.sendPhz(5000, 'Ready');
                node.setVisible(false);
            });
            //快速开局
            TouchUtil.setOnclickListener(self.$('FunctionBtn.btn_quick'), function (node) {
                network.sendPhz(5000, 'QuickStart/3/' + self.getQuickStartOption());
                node.setVisible(false);
            });

            //退出
            TouchUtil.setOnclickListener(self.$('FunctionBtn.bottomCenter.btn_tuichu'), function () {
                showMessageBox('确定要退出房间吗?', function () {
                    network.sendPhz(3003, 'Quit/' + gameData.roomId);
                });
            });
            //解散
            TouchUtil.setOnclickListener(self.$('FunctionBtn.bottomCenter.btn_jiesan'), function () {
                if (window.inReview)
                    network.sendPhz(3003, 'Discard/' + gameData.roomId);
                else
                    showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                        network.sendPhz(3003, 'Discard/' + gameData.roomId);
                    });
            });
            //排序牌
            TouchUtil.setOnclickListener(self.$('FunctionBtn.btn_refresh'), function () {
                ZiPaiRoomData.hz_sortId = (ZiPaiRoomData.hz_sortId + 1) % 3;
                cc.sys.localStorage.setItem('hz_sortId', ZiPaiRoomData.hz_sortId);
                self.zipaiManager.resetCards();
            });
            //刷新
            TouchUtil.setOnclickListener(self.$('guding.btn_shuaxin'), function () {
                network.disconnect();
            });
            //复制房间
            TouchUtil.setOnclickListener(self.$('FunctionBtn.bottomCenter.btn_copy'), function () {
                ShareUtil.CopyRoomId();
            }, {});
            //邀请
            TouchUtil.setOnclickListener(self.$('FunctionBtn.bottomCenter.btn_invite'), function () {
                ShareUtil.ShareRoomId(gameData.roomId, gameData.wanfaDesp, gameData.playerNum, gameData.players.length);
            });
            //聊天
            TouchUtil.setOnclickListener(self.$('FunctionBtn.btn_chat'), function () {
                showWindow('ChatWindow');
            });
            //定位
            // TouchUtil.setOnclickListener(this.safebtn, function () {
            //     showWindow('PlayerInfoLocationWindow', false, that);
            // });
            //设置
            TouchUtil.setOnclickListener(self.$('guding.btn_Setting'), function () {
                showWindow('SettingWindow_qylds', Setting_TYPE.Table_Hz);
            });
            //切换背景
            TouchUtil.setOnclickListener(self.$('guding.btn_dingwei'), function () {
                showWindow('PlayerInfoLocationWindow', false, self);
            });
            //离开
            TouchUtil.setOnclickListener(self.$('guding.btn_likai'), function () {
                // 申请投票解散
                var fun1 = function () {
                    if (window.inReview)
                        network.sendPhz(5000, 'Vote/quit/1/0/0');
                    else
                        showMessageBox('确定要申请解散房间吗？', function () {
                            network.sendPhz(5000, 'Vote/quit/1/0/0');
                        });
                };
                //房主解散房间
                var fun2 = function () {
                    if (window.inReview)
                        network.sendPhz(3003, 'Discard/' + gameData.roomId);
                    else
                        showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                            network.sendPhz(3003, 'Discard/' + gameData.roomId);
                        });
                };
                //其他玩家退出房间
                var func3 = function () {
                    showMessageBox('确定要退出房间吗?', function () {
                        network.sendPhz(3003, 'Quit/' + gameData.roomId);
                    });
                };
                if (self.zipaiManager.isGameStart) {
                    fun1();
                } else {
                    if (self.zipaiManager.Owner == gameData.uid) {
                        fun2();
                    } else {
                        func3();
                    }
                }

            });

            //举手
            TouchUtil.setOnclickListener(self.$('jushou'), function (node) {
                self.playJSEffect('jushou', gameData.sex);
                network.sendPhz(5000, 'Jushou/1');
            }, {});
            //不举手
            TouchUtil.setOnclickListener(self.$('bujushou'), function (node) {
                network.sendPhz(5000, 'Jushou/2');
            }, {});
        },
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
            this.initTouch();
            network.start();
        },
        onExit: function () {
            eventManager.removeListeners(this);
            cc.Layer.prototype.onExit.call(this);
        },
        /**
         * 获取房间状态
         * @returns {number|*}
         */
        getRoomState: function () {
            return this.zipaiManager.GameStatus;
        },
        setZipaiManager: function (data, roomDataType) {
            this.zipaiManager = new ZiPaiManager(data, roomDataType,this);
            this.addComponent(this.zipaiManager);
        },
        /**
         * 构造
         * @param data
         * @param roomDataType
         * @returns {boolean}
         */
        ctor: function (data, roomDataType) {
            this._super();
            if(window.zipaiManager){
                window.zipaiManager.onExit();
                delete window.zipaiManager
            }
            this.setZipaiManager(data, roomDataType);
            mAction.initGame();
            window.zipaiManager = this.zipaiManager;
            this.initEvent();
            loadCCSTo(this._ccsFileName, this, "Layer");
            this.scheduleUpdate();
            getVersion('zipai');
            return true;
        },
        /**
         * 获取根节点
         * @returns {*|ccui.Widget|cc.Node}
         */
        getRootNode: function () {
            return this.getChildByName("Layer");
        },
        /**
         * 初始化界面
         */
        initPlayerInfoNode: function () {
            var self = this;
            self.playersNum = this.zipaiManager.PlayersNum;
            self.PlayerInfoNode = self.$('PlayerInfo.PlayerInfoNode.table' + zipai.curMaxPlayerNum);
            self.PlayerInfoNode.setVisible(true);
            self.PlayerInfoNode.setSwallowTouches(false);
            self.PosNode = self.$('pos' + self.playersNum, self.PlayerInfoNode);
            //table4.pos位置变更
            if (zipai.curMaxPlayerNum == 4) {
                if (self.playersNum == 3){
                    var tmpName = "tmpName";
                    //info
                    self.$("info3",self.PlayerInfoNode ).setName(tmpName);
                    self.$("info1",self.PlayerInfoNode ).setName("info3");
                    self.$("info2",self.PlayerInfoNode ).setName("info1");
                    self.$(tmpName,self.PlayerInfoNode ).setName("info2");
                    //replay_act
                    self.$("replay_act3",self.PlayerInfoNode ).setName(tmpName);
                    self.$("replay_act1",self.PlayerInfoNode ).setName("replay_act3");
                    self.$("replay_act2",self.PlayerInfoNode ).setName("replay_act1");
                    self.$(tmpName,self.PlayerInfoNode ).setName("replay_act2");
                    //out
                    self.$("out3",self.PosNode ).setName(tmpName);
                    self.$("out1",self.PosNode ).setName("out3");
                    self.$("out2",self.PosNode ).setName("out1");
                    self.$(tmpName,self.PosNode ).setName("out2");
                    //open
                    self.$("open3",self.PosNode ).setName(tmpName);
                    self.$("open1",self.PosNode ).setName("open3");
                    self.$("open2",self.PosNode ).setName("open1");
                    self.$(tmpName,self.PosNode ).setName("open2");
                    //nCards0
                    self.$("nCards3",self.PosNode ).setName(tmpName);
                    self.$("nCards1",self.PosNode ).setName("nCards3");
                    self.$("nCards2",self.PosNode ).setName("nCards1");
                    self.$(tmpName,self.PosNode ).setName("nCards2");
                }
                else if (self.playersNum == 2){
                    var tmpName = "tmpName";
                    //info
                    self.$("info1",self.PlayerInfoNode ).setName(tmpName);
                    self.$("info3",self.PlayerInfoNode ).setName("info1");
                    self.$(tmpName,self.PlayerInfoNode ).setName("info3");
                    //replay_act
                    self.$("replay_act1",self.PlayerInfoNode ).setName(tmpName);
                    self.$("replay_act3",self.PlayerInfoNode ).setName("replay_act1");
                    self.$(tmpName,self.PlayerInfoNode ).setName("replay_act3");
                    //out
                    self.$("out1",self.PosNode ).setName(tmpName);
                    self.$("out3",self.PosNode ).setName("out1");
                    self.$(tmpName,self.PosNode ).setName("out3");
                    //open
                    self.$("open1",self.PosNode ).setName(tmpName);
                    self.$("open3",self.PosNode ).setName("open1");
                    self.$(tmpName,self.PosNode ).setName("open3");
                    //nCards0
                    self.$("nCards1",self.PosNode ).setName(tmpName);
                    self.$("nCards3",self.PosNode ).setName("nCards1");
                    self.$(tmpName,self.PosNode ).setName("nCards3");
                }
            }

            for (var i = 0; i < zipai.curMaxPlayerNum; i++) {
                var infoNode = self.$('info' + i, self.PlayerInfoNode);
                infoNode.setVisible(false);
                // infoNode.getChildByName('txtHX').setVisible(false);
                // infoNode.getChildByName('txtHX_value').setVisible(false);
                infoNode.getChildByName('timeBg').setVisible(false);
                infoNode.getChildByName('ChatInfo').setVisible(false);
                infoNode.getChildByName('ok').setVisible(false);
                infoNode.getChildByName('offline').setVisible(false);
                infoNode.getChildByName('zhuang').setVisible(false);
                infoNode.getChildByName('fangzhu').setVisible(false);


                var headf = infoNode.getChildByName('headf');
                var guangquan = playAnimScene(headf, zipai.res.PhzHead_json, headf.getContentSize().width / 2, headf.getContentSize().height / 2, true);
                guangquan.setName('guangquan');
                guangquan.setVisible(false);


                var openNode = new OpenCards();
                openNode.setName('OpenCards');
                openNode.setPos(i);
                self.$('open' + i, this.PosNode).addChild(openNode);


                var outNode = new OutCards();
                outNode.setName('OutCards');
                outNode.setPos(i);
                self.$('out' + i, this.PosNode).addChild(outNode);
            }

            this.actCard = new Card();
            this.addChild(this.actCard);
            this.showCard = new Card();
            this.PlayerInfoNode.getChildByName('showCard').addChild(this.showCard);
        },
        initializeUI: function () {
            var self = this;
            this.startTime();
            this.startSignal();
            this.txtRound = self.$('guding.txtRound');
            self.$('guding.lb_roomid').setString(this.zipaiManager.RoomID);
            self.$('RoomInfo.lb_wanfa').setString(this.zipaiManager.WanfaDesp);


            this.game_zhang = self.$('RoomInfo.game_zhang');
            this.txtCardCount = self.$('RoomInfo.game_zhang.txtCardCount');

            this.jushou = self.$('jushou');
            this.bujushou = self.$('bujushou');
            this.jushou.setVisible(false);
            this.bujushou.setVisible(false);

            this.cd = self.$('RoomInfo.cd');
            this.cdtext = self.$('RoomInfo.cd.cdtext');
            this.cd.setVisible(false);
            //进度条指针
            var cdbar = new cc.ProgressTimer(cc.Sprite.create(zipai.dynamicRes + 'greenquan.png'));
            cdbar.setPosition(cc.p(this.cd.getContentSize().width / 2, this.cd.getContentSize().height / 2 + 2));
            cdbar.setType(cc.ProgressTimer.TYPE_RADIAL);
            cdbar.setMidpoint(cc.p(0.5, 0.5));
            cdbar.setReverseDirection(true);
            cdbar.runAction(
                cc.progressTo(0.1, 100)
            );
            this.cd.addChild(cdbar);
            this.cdbar = cdbar;

            this.tingNode = self.$('ting_node');

            this.tipLine = self.$('RoomInfo.tipLine');
            this.tipLine.setVisible(false);
            this.CHUPAI_HEIGHT = this.tipLine.getPositionY();

            this.nAction = self.$('nAction');
            this.listActBtn = [];
            var btnName = {
                1 : "sp_hu",
                2 : "sp_chi",
                3 : "sp_peng",
                4 : "sp_guo"
            };
            for (var i = 1; i < 6; i++) {
                (function (i) {
                    var bt = self.$('nAction.bt' + i);
                    var aniPos = self.$('aniPos', bt);
                    if (btnName[i]) {
                        aniPos.removeAllChildren();
                        playAnimScene(aniPos, zipai.res[btnName[i]], 0, 0, true, function () {});
                    }
                    bt.setVisible(false);
                    TouchUtil.setOnclickListener(bt, function () {
                        self.onActionBtn(i, bt);
                    }, {});
                    self.listActBtn.push(bt);
                })(i);
            }

            self.$('FunctionBtn.bottomCenter.btn_zhunbei').setVisible(false);
            self.$('FunctionBtn.btn_refresh').setVisible(false);

            self.imgAct = self.$('imgAct');
            self.nLaizi = self.$('nLaizi');
            self.nChiList = self.$('nChiList');
            self.nOpenOutLayer = self.$('nOpenOutLayer');
            self.huNode = self.$('HuNode', this.nOpenOutLayer);


            this.panelResult = self.$('PanelResult');
            this.panelResult.setLocalZOrder(10);
            this.panelResult.setVisible(false);
            this.btn_continue = self.$('PanelResult.btn_continue');
            TouchUtil.setOnclickListener(self.$('PanelResult.btn_result_bg'), function () {
                self.showGameResult(false);
            });
            TouchUtil.setOnclickListener(this.btn_continue, function () {
                self.showRoomClean();
                self.onReady();
            });

            self.initPlayerInfoNode();
            self.enableChuPai();
            self.clearRoom();
            self.changeBgm();
            this.countDown = this.countDown();
            self.initLog();
        },
        initLog: function () {
            var self = this;
            var game_title = self.$('RoomInfo.game_title');
            var resLog = zipai.res.logo_HGW;
            switch (gameData.mapId) {
                case app.map_id.HUAIHUA_QUANMINGTANG:
                    resLog = zipai.res.logo_QMT;
                    break;
                case app.map_id.HUAIHUA_HONGGUAIWAN:
                    resLog = zipai.res.logo_HGW;
                    break;
            }
            game_title.setTexture(resLog);
        },
        /**
         * 切换胡息显示
         */
        changeHuXi: function () {
            if (this.HuXiNode) {
                this.HuXiNode.setVisible(settingData.showhuxi);
            }
        },
        /**
         * 切换背景音乐
         */
        changeBgm: function () {
            //背景声音
            if (settingData.jingyinopen) {
                stopMusic();
            } else if (settingData.musicvoice) {
                var setting_bgm = settingData.local_bgMusic[gameData.mapId] || 1;
                playMusic("vbg_zipai" + setting_bgm);
            }
        },
        /**
         * 刷新分数
         */
        updateScore: function (pos) {
            var infoNode = this.$('info' + pos, this.PlayerInfoNode);
            var txtScore = infoNode.getChildByName('txtScore');
            var uid = this.zipaiManager.g_pos_to_uid[pos];
            var score = this.zipaiManager.g_uid_to_Score[uid] || 0;
            txtScore.setString(score);
        },
        /**
         * 重置房间信息
         */
        clearRoom: function (roundNotAdd) {
            for (var i = 0; i < this.playersNum; i++) {
                this.getCardsNode(i).removeAllChildren();
                this.getOpenNode(i).removeAllChildren();
                this.getOutNode(i).removeAllChildren();

                var infoNode = this.$('info' + i, this.PlayerInfoNode);
                var txtHX = infoNode.getChildByName('txtHX');
                var txtHX_value = infoNode.getChildByName('txtHX_value');

                txtHX.setString('胡息');
                txtHX_value.setString('');

                // if (mRoom.wanfatype == mRoom.LEIYANG) {
                //     txtHX.setString('胡子');
                //     txtHX_value.setString('0');
                // } else if (mRoom.wanfatype == mRoom.YOUXIAN || mRoom.wanfatype == mRoom.HENGYANG || mRoom.wanfatype == mRoom.MAOHUZI) {
                //     txtHX.setString('胡子');
                //     txtHX_value.setString('0');
                // } else if (mRoom.wanfatype == mRoom.WEIMAQUE) {
                //     txtHX.setString('硬息');
                //     txtHX_value.setString('0');
                // } else {
                //     txtHX.setString('胡息');
                //     txtHX_value.setString('0');
                // }
                if (this.zipaiManager.isGameStart) {
                    this.updateScore(i);
                }
            }
            if (this.zipaiManager.Sipai) {
                this.getCardsNode(2).removeAllChildren();
            }
            this.hideImaAct();
            this.actCard.setVisible(false);
            this.showCard.setVisible(false);
            this.game_zhang.setVisible(false);
            this.secondsLeft = 0;
            this.turnPos = 0;
            this.nAction.setVisible(false);
            this.huNode.removeAllChildren();
            this.tingNode.setVisible(false);
            mAction.initGame();
            this.txtRound.setString(this.zipaiManager.CurRound + '/' + this.zipaiManager.ZongRound);
            this.isTurnOut = false;
            this.isTurnIn = false;
            ZiPaiRoomData.gameOverHuInfo = null;
            this.Freeze = null;//冻结字段
            this.Notice = null;
            this.panelResult.setVisible(false);
            this.hideCardsHuXi();
            this.removeXing();
            this.showTingPaiOnDesk();
        },
        removeXing:function () {
            var game_zhang = this.$('RoomInfo.game_zhang');
            mEffect.fanxing(null,game_zhang,null,true)
        },
        /**
         * 更新举手状态
         */
        setJushouStatus: function () {
            var Users = this.zipaiManager.JushouStatus;
            var canchupai = true;
            if (Users) {
                for (var i = 0; i < Users.length; i++) {
                    this.setJushou(Users[i]['UserID'], Users[i]['IsSet'], Users[i]['CanSet']);
                    if (Users[i]['CanSet'] == 1 && Users[i]['IsSet'] == 0) {
                        canchupai = false;
                    }
                }
            }
            //this.setMyCardsTouch(canchupai);
        },
        /**
         * 设置举手按钮
         * @param uid
         * @param isset
         * @param canset
         * @param status
         */
        setJushou: function (uid, isset, canset, status) {
            if (gameData.mapId != app.map_id.LEIYANGZIPAI) {
                return;
            }
            var row = this.zipaiManager.g_uid_to_pos[uid];
            var infoNode = this.$('info' + row, this.PlayerInfoNode);
            var head = infoNode.getChildByName('head');
            //举手中
            var jushou = head.getChildByName('jushou');
            if (!jushou) {
                jushou = new cc.Sprite(zipai.dynamicRes + 'jushouzhong2.png');
                jushou.setName('jushou');
                jushou.setAnchorPoint(cc.p(0.5, 0.5));
                var jushoupos = cc.p(150, 150);
                if (row == 1) {
                    jushoupos = cc.p(-20, 10);
                } else if (row == 2) {
                    jushoupos = cc.p(120, 30);
                }
                jushou.setPosition(jushoupos);
                head.addChild(jushou);
                jushou.setVisible(false);
            }
            if (jushou) {
                //已举手
                if (isset == 1) {
                    var yjushoupos = cc.p(70, 60);
                    jushou.setVisible(true);
                    jushou.setTexture(zipai.dynamicRes + 'yijushou3.png');
                    jushou.setPosition(yjushoupos);
                }
                //举手中
                if (canset == 1 && isset == 0) {
                    jushou.setVisible(true);
                    jushou.setTexture(zipai.dynamicRes + 'jushouzhong2.png');
                }
                //不举手
                if (isset == 2) {
                    jushou.setVisible(false);
                }
            }
            if (gameData.uid == uid) {
                if (canset == 1 && isset == 0) {
                    this.jushou.setVisible(true);
                    this.bujushou.setVisible(true);
                } else {
                    this.jushou.setVisible(false);
                    this.bujushou.setVisible(false);
                }
            }
            if (status == false) {
                jushou.setVisible(false);
            }
        },
        /**
         * 更新切牌状态
         */
        setUpQiePai: function (data) {
            this.setRoomState();
            data.endPos = this.game_zhang.getParent().convertToWorldSpace(this.game_zhang.getPosition());
            if (!this.QiePaiWindow) {
                this.QiePaiWindow = showWindow('ZiPai_QiePaiWindow', data, this);
            } else {
                this.QiePaiWindow.setData(data, this);
            }
            this.QiePaiWindow.setVisible(true);
        },
        setQieCard: function (cardCount) {
            var self = this;
            self.game_zhang.setVisible(true);
            self.txtCardCount.setString(cardCount);
            var sceneid = settingData.local_table[gameData.mapId] || 0;
            var index = parseInt(cardCount / 10) + 1;
            if (index > 8) {
                index = 8;
            }
            self.game_zhang.setTexture(zipai.res['fapai_' + sceneid + '_' + index]);
            if (cardCount == 80 && self.QiePaiWindow) {
                setTimeout(function () {
                    self.QiePaiWindow.removeFromParent(true);
                    self.QiePaiWindow = null;
                    network.start();
                }, 500);
            }
        },
        /**
         * 更新报警状态
         */
        setUpBaojing: function () {
            var Users = this.zipaiManager.BaojingData;
            for (var i = 0; i < Users.length; i++) {
                this.setBaojing(Users[i]['UserID'], Users[i]['Stat']);
            }
        },
        /**
         * 报警
         * @param uid
         * @param status
         */
        setBaojing: function (uid, status) {
            var row = this.zipaiManager.g_uid_to_pos[uid];
            var infoNode = this.$('info' + row, this.PlayerInfoNode);
            var head = infoNode.getChildByName('head');
            //举手中
            var baojing = head.getChildByName('baojing');
            if (!baojing) {
                baojing = new cc.Sprite(zipai.dynamicRes + 'baojingzhong1.png');
                baojing.setName('baojing');
                baojing.setAnchorPoint(cc.p(0.5, 0.5));
                var jushoupos = cc.p(50, 150);
                if (row == 0) {
                    jushoupos = cc.p(340, 60);
                } else if (row == 1) {
                    jushoupos = cc.p(-180, 60);
                } else if (row == 3 || row == 2) {
                    jushoupos = cc.p(50, -30);
                }
                baojing.setPosition(jushoupos);
                head.addChild(baojing);
                baojing.setVisible(false);
            }
            if (baojing) {
                if (status == 2) {
                    //已报警
                    baojing.setVisible(true);
                    baojing.setTexture((row == 2 || row == 3)
                        ? zipai.dynamicRes + 'baojing1.png' : zipai.dynamicRes + 'baojing2.png');
                } else if (status == 1) {
                    //报警中
                    baojing.setVisible(true);
                    baojing.setTexture((row == 2 || row == 3)
                        ? zipai.dynamicRes + 'baojingzhong1.png' : zipai.dynamicRes + 'baojingzhong2.png');
                } else {
                    baojing.setVisible(false);
                }
            }
            if (uid == gameData.uid && status == 1) {
                //0:不能设置报警  1:能设置，但是没有设置  2:已经报警  3:选择不报警
                showMessageBox('选择报警或者不报警，确定（报警），取消（不报警）。', function () {
                    network.sendPhz(5000, 'Baojing/2');
                }, function () {
                    network.sendPhz(5000, 'Baojing/3');
                });
            }
        },
        /**
         * 游戏准备
         */
        onReady: function () {
            this.clearRoom();
            network.sendPhz(5000, 'Ready');
            var players = this.zipaiManager.PlayerInfos;
            for (var i = 0; i < players.length; i++) {
                this.setJushou(players[i].ID, 0, 0, false);//举手
                this.setBaojing(players[i].ID, 0);//报警
            }
        },
        addPlayerBackWindow:function () {
            var self = this;
            if (self.zipaiManager.isReplay) {
                showWindow('Zipai_PlayerBackWindow', self.zipaiManager.roomReplayDate, this);
            }
        },
        /**
         * 加载资源结束
         */
        onCCSLoadFinish: function () {
            var self = this;
            setDesignResolution(this.getRootNode());
            batchSetChildrenZorder(this.getRootNode(), {
                btn_zhunbei: 20
                // info0: 1, info1: 1, info2: 1, info3: 1,
                // info_n0: 2, info_n1: 2, info_n2: 20, info_n3: 2,
                // row2: 10,
                // cpghg: 11, piao_bar: 12,
                // btn_bg: 30, btn_control_btns: 34,
                // hu_type_layer: 99, btn_zhunbei: 20, change_sroce_node: 50,

            });
            //
            // that.addPlayBackLayer();

            self.$ = create$(this.getRootNode());
            this.initializeUI();
            this.changeBg();
            MicLayer.init(self.$('FunctionBtn.btn_mic'), this);
            this.setUpPlayers();
            this.setRoomState();
            if (self.zipaiManager.isReconnect && self.zipaiManager.isGameStart) {
                self.setReconnectGame();
            }
            this.addPlayerBackWindow()
        },
        setLeftCard: function () {
            this.game_zhang.setVisible(this.zipaiManager.LeftCardCount >= 0 && this.zipaiManager.isGameStart);
            this.txtCardCount.setString(this.zipaiManager.LeftCardCount);
            var sceneid = settingData.local_table[gameData.mapId] || 0;
            //暂时设置成0
            sceneid = 0;
            var index = parseInt(this.zipaiManager.LeftCardCount / 10) + 1;
            if (index > 8) {
                index = 8;
            }
            this.game_zhang.setTexture(zipai.res['fapai_' + sceneid + '_' + index]);
        },
        setReconnectGame: function () {
            var self = this;
            self.setUpPiao();
            self.setUpCards();
            self.setDisconnect();
            self.setLeftCard();
            self.setAllOutCards();
            self.setAllOpenCards();
            self.setFreezeCard();
            for (var i = 0; i < self.playersNum; i++) {
                self.setUpHX(i)
            }
            self.setRoundInfo();
        },
        setUpPiao:function () {

        },
        /**
         * 设置回合信息
         */
        setRoundInfo: function () {
            if (this.zipaiManager.isGameStart) {
                var roundInfo = this.zipaiManager.RoundInfo;
                var card = roundInfo['Card'];
                var from = roundInfo['From'];
                var mo = roundInfo['Mo'];//
                var seq = roundInfo['Seq'];//第几轮
                if (card != void 0) {
                    if (card == 0) {
                        this.setTurnOut();
                    } else {
                        var userPos = this.zipaiManager.g_uid_to_pos[from];
                        var isMo = (mo == 1);
                        if (seq == 0) {
                            this.showLZCardAtPos(card, userPos, isMo);
                        } else {
                            this.showCardAtPos(card, userPos, isMo);
                        }
                        this.setTurnIn();
                    }
                }
                this.setUpGameStart();
            }
        },
        /**
         * 设置所有玩家弃牌
         */
        setAllOutCards: function () {
            for (var i = 0; i < this.playersNum; i++) {
                var outCards = this.getOutNode(i);
                outCards.removeAllChildren();
                var uid = this.zipaiManager.g_pos_to_uid[i];
                var DiscardCards = this.zipaiManager.g_uid_to_DiscardCards[uid];
                if (DiscardCards) {
                    for (var j = 0; j < DiscardCards.length; j++) {
                        var card = DiscardCards[j];
                        outCards.addCard(card);
                    }
                }
            }
        },
        setAllOpenCards: function () {
            for (var i = 0; i < this.playersNum; i++) {
                var openCards = this.getOpenNode(i);
                openCards.removeAllChildren();
                var uid = this.zipaiManager.g_pos_to_uid[i];
                var menzi = this.zipaiManager.g_uid_to_Menzi[uid];
                if (menzi) {
                    for (var j = 0; j < menzi.length; j++) {
                        var mz = menzi[j];
                        if (mz.Type == '吃') {
                            //吃的牌特殊显示
                            var chiCard = mz['Chi'];
                            for (var k = 0; k < mz['Cards'].length; k += 3) {
                                var cards = [mz['Cards'][k], mz['Cards'][k + 1], mz['Cards'][k + 2]];
                                var typ = mCard.getComboType(cards, false);
                                //吃的放在第一个位置
                                for (var x = 0; x < cards.length; x++) {
                                    if (chiCard == cards[x]) {
                                        var tmp = cards[x];
                                        for (var y = x + 1; y < 3; y++) {
                                            cards[y - 1] = cards[y];
                                        }
                                        cards[2] = tmp;
                                    }
                                }
                                openCards.addCards(cards, typ, false, false);
                            }
                        } else if (mz.Type == '话') {
                            for (var k = 0; k < mz['Cards'].length; k += 3) {
                                var cards = [mz['Cards'][k], mz['Cards'][k + 1], mz['Cards'][k + 2]];
                                var typ = mCard.getComboType(cards, false);
                                openCards.addCards(cards, typ);
                            }
                        } else {
                            var typ = mCard.comboTypes_ZN[mz.Type];
                            if (typ != mCard.comboTypes.kan) {
                                openCards.addCards(mz['Cards'], mCard.comboTypes_ZN[mz.Type]);
                            }
                        }
                    }
                }
            }
        },
        /**
         * 切换牌桌背景图
         */
        changeBg: function () {
            if(cc.isUndefined(settingData.local_table[gameData.mapId])){
                var local_table = settingData.local_table;
                local_table[gameData.mapId] = 0;
                settingData.local_table = local_table;
            }
            var sceneid = settingData.local_table[gameData.mapId];
            var bg = this.$('RoomInfo.bg');
            bg.setTexture(zipai.res['roomBg_' + sceneid]);
            this.setCardBackImg();
        },
        //更换背景时更换牌背
        setCardBackImg: function () {
            for (var i = 0; i < this.zipaiManager.PlayersNum; i++) {
                var open = this.getOpenNode(i);
                var openChileren = open.getChildren();
                for (var j = 0; j < openChileren.length; j++) {
                    openChileren[j].resetCardBackImg();
                }
                var out = this.getOutNode(i);
                var outChileren = out.getChildren();
                for (j = 0; j < outChileren.length; j++) {
                    outChileren[j].resetCardBackImg();
                }
            }
            if (this.zipaiManager.Sipai) {
                var CardsNode = this.getCardsNode(2);
                var cardChileren = CardsNode.getChildren();
                for (j = 0; j < cardChileren.length; j++) {
                    cardChileren[j].resetCardBackImg();
                }
            }
            //剩余张数的牌背更换牌背
            this.setLeftCard();
        },
        /**
         * 设置玩家头像信息
         */
        setUpPlayers: function () {
            var self = this;
            for (var i = 0; i < zipai.curMaxPlayerNum; i++) {
                var row = i;
                var info = this.zipaiManager.g_pos_to_info[row];
                this.setPlayerAvator(row, info);
                this.updateScore(row);
            }
            cc.log(gameData.players.length + "======" + this.zipaiManager.PlayersNum);
            var isQuickBtn = (this.zipaiManager.PlayersNum > 2
            && this.zipaiManager.QuickStart
            && gameData.players.length > 1
            && gameData.players.length < this.zipaiManager.PlayersNum);

            self.$('FunctionBtn.btn_quick').setVisible(isQuickBtn);
            self.$('RoomInfo.lb_wanfa').setString(self.handleWanfaDesp(this.zipaiManager.WanfaDesp));
        },
        /**
         * 设置玩家准备状态
         */
        setPlayersStatus: function () {
            var self = this;
            var btn_zhunbei = self.$('FunctionBtn.bottomCenter.btn_zhunbei');
            btn_zhunbei.setVisible(this.zipaiManager.isShowReadyBtn && this.zipaiManager.GameStatus == 0 && !this.panelResult.isVisible());
            for (var i = 0; i < this.zipaiManager.PlayersStatus.length; i++) {
                var ReadyData = this.zipaiManager.PlayersStatus[i];
                var uid = ReadyData.UserID;
                self.setReady(uid, (ReadyData['ReadyValue'] && this.zipaiManager.GameStatus == 0));
            }
        },
        setRoomState: function () {
            var self = this;
            self.$('FunctionBtn.bottomCenter.btn_invite').setVisible(!self.zipaiManager.isGameStart && !self.zipaiManager.isReplay);
            //复制房间号展示位置变更到邀请窗口
            //self.$('FunctionBtn.btn_copy').setVisible(!self.zipaiManager.isGameStart && !self.zipaiManager.isReplay);
            self.$('FunctionBtn.bottomCenter.img_dengdaijiaru').setVisible(!self.zipaiManager.isGameStart && !self.zipaiManager.isReplay);
            self.$('FunctionBtn.bottomCenter.btn_tuichu').setVisible(!self.zipaiManager.isGameStart && self.zipaiManager.Owner != gameData.uid && !self.zipaiManager.isReplay);
            self.$('FunctionBtn.bottomCenter.btn_jiesan').setVisible(!self.zipaiManager.isGameStart && self.zipaiManager.Owner == gameData.uid && !self.zipaiManager.isReplay);
        },
        /**
         * 设置准备状态
         * @param uid
         * @param visible
         */
        setReady: function (uid, visible) {
            if (gameData.players && gameData.players.length) {
                for (var i = 0; i < gameData.players.length; i++) {
                    if (uid == gameData.players[i]['ID'] || uid == gameData.players[i]['uid']) {
                        if (visible) {
                            gameData.players[i]['ready'] = 1;
                        } else {
                            gameData.players[i]['ready'] = 0;
                        }
                        break;
                    }
                }
            }
            var self = this;
            var row = this.zipaiManager.g_uid_to_pos[uid];
            var infoNode = self.$('info' + row, self.PlayerInfoNode);
            if (infoNode) {
                var ok = infoNode.getChildByName('ok');
                ok.setVisible(visible);
            }
        },
        hideOk: function () {
            var self = this;
            for (var i = 0; i < this.zipaiManager.PlayerInfos.length; i++) {
                var infoNode = self.$('info' + i, self.PlayerInfoNode);
                if (infoNode) {
                    infoNode.getChildByName('ok').setVisible(false);
                }
            }
        },
        /**
         * 设置离线状态
         */
        setDisconnect: function () {
            var self = this;
            for (var i = 0; i < this.zipaiManager.PlayerInfos.length; i++) {
                var uid = this.zipaiManager.PlayerInfos[i]['ID'];
                var row = this.zipaiManager.g_uid_to_pos[uid];
                var offline = this.zipaiManager.g_uid_to_offline[uid];
                var infoNode = self.$('info' + row, self.PlayerInfoNode);
                if (infoNode) {
                    var uiOffline = infoNode.getChildByName('offline');
                    var time = uiOffline.getChildByName('time');
                    if (offline && !uiOffline.isVisible()) {
                        time.timeNum = -1;
                        self.setOfflineTime(time);
                    }
                    uiOffline.setVisible(offline);
                }
            }
        },
        /**
         * 设置头像
         * @param row
         * @param info
         */
        setPlayerAvator: function (row, info) {
            var self = this;
            var infoNode = self.$('info' + row, self.PlayerInfoNode);
            infoNode.setVisible(!!info);
            if (info) {
                var txtHX = infoNode.getChildByName('txtHX');
                var txtHX_value = infoNode.getChildByName('txtHX_value');
                var txtUserName = infoNode.getChildByName('txtUserName');
                var txtScore = infoNode.getChildByName('txtScore');
                var head = infoNode.getChildByName('head');
                var ChatInfo = infoNode.getChildByName('ChatInfo');

                loadHeadImage(decodeURIComponent(info.HeadIMGURL || info.headimgurl), head, true);
                txtUserName.setString(ellipsisStr(info.NickName || info.nickname, 5));

                TouchUtil.setOnclickListener(head, function () {
                    if (!self.zipaiManager.isReplay) {
                        self.showPlayerInfoPanel(info);
                    }
                })
            }
        },
        /**
         * 显示玩家信息
         * @param playerInfo
         */
        showPlayerInfoPanel: function (playerInfo) {
            var that = this;
            playerInfo.uid = playerInfo.ID;
            playerInfo.nickname = playerInfo.NickName;
            playerInfo.ip = playerInfo.IP;
            playerInfo.headimgurl = playerInfo.HeadIMGURL;
            playerInfo.sex = playerInfo.Sex;
            network.send(3018, {cmd: 'queryEmoji', uid: gameData.uid, room_id: gameData.roomId, showOption: 32767});
            showWindow('PlayerInfoInGameWindow', playerInfo, that);
        },
        /**
         * 手型滑动动画
         */
        fingerAni: function (isShow) {
            var fingerAni = this.getChildByName('showAni');
            if (fingerAni == null || fingerAni == undefined) {
                var ccsScene = ccs.load(res.PhzShou_json, getCCSFileNamePath(res.PhzShou_json));
                fingerAni = ccsScene.node;
                fingerAni.setName('showAni');
                fingerAni.setPosition(cc.p(1100, 200));
                this.addChild(fingerAni);
                fingerAni.runAction(ccsScene.action);
                ccsScene.action.play('action', true);
            }
            fingerAni.setVisible(isShow);
        },
        setCDTime: function (cd) {
            var self = this;
            for (var i = 0; i < zipai.curMaxPlayerNum; i++) {
                var infoNode = self.$('info' + i, self.PlayerInfoNode);
                if (infoNode) {
                    var time = infoNode.getChildByName('timeBg').getChildByName('time');
                    time.setString(cd < 10 ? "0" + cd : cd);
                }
            }
        },
        showCDTime: function (row) {
            var self = this;
            for (var i = 0; i < zipai.curMaxPlayerNum; i++) {
                var infoNode = self.$('info' + i, self.PlayerInfoNode);
                var timeBg = infoNode.getChildByName('timeBg');
                timeBg.setVisible(row == i);
                var guangquan = infoNode.getChildByName('headf').getChildByName('guangquan');
                if (guangquan) {
                    guangquan.setVisible(row == i);
                }
            }
        },
        /**
         * 倒计时
         * @returns {Function}
         */
        countDown: function () {
            var self = this;
            var timer = null;
            return function (row) {
                if (self.zipaiManager.isReplay || self.secondsLeft == -1) {
                    self.showCDTime(-1);
                    return;
                }
                self.showCDTime(row);
                if (timer) {
                    clearInterval(timer);
                    timer = null;
                }
                self.setCDTime(self.secondsLeft);
                timer = setInterval(function () {
                    if (!cc.sys.isObjectValid(self.cdtext)) {
                        if (timer) {
                            clearInterval(timer);
                            timer = null;
                        }
                        return;
                    }
                    if (!self.cdtext) {
                        clearInterval(timer);
                        timer = null;
                        return;
                    }
                    var hasCard = (self.zipaiManager.SeverCardList || self.zipaiManager.SeverCardList.length > 0);
                    if (self.secondsLeft > 0 && hasCard) {
                        --self.secondsLeft;
                        self.setCDTime(self.secondsLeft);
                        // self.cdtext.setString(self.secondsLeft < 10 ? "0" + self.secondsLeft : self.secondsLeft);
                        //
                        // var bili = self.secondsLeft / 25 * 100;
                        // self.cdbar.runAction(
                        //     cc.progressTo(1, bili)
                        // );
                        // var cdbarsprite = self.cdbar.getSprite();
                        // cdbarsprite.setTexture((self.secondsLeft < 13) ? res.redquan_png : res.greenquan_png);
                        if (self.secondsLeft >= 0 && self.secondsLeft <= 5) {
                            playEffect('vCountDown');
                        }

                        if (self.secondsLeft == 0) {
                            if (self.isTurnOut == true || self.isTurnIn == true)
                                DeviceUtil.vibrate();
                            clearInterval(timer);
                        }
                        if (self.secondsLeft == 14) {
                            if (self.isTurnOut)
                                self.fingerAni(true);
                        }
                    } else {
                        self.setCDTime(self.secondsLeft);
                        //self.cdtext.setString(self.secondsLeft < 10 ? "0" + self.secondsLeft : self.secondsLeft);
                    }
                }, 1000);
            }
        },
        /**
         * 游戏时间、电池显示
         */
        startTime: function () {
            var that = this;
            var interval = null;
            var flag = true;
            var lbTime = that.$('guding.lb_time');
            if (that.isReplay) {
                if (cc.sys.isObjectValid(lbTime)) {
                    lbTime.setString('--:--');
                }
                return;
            }
            var updTime = function () {
                //显示电池电量
                var battery = that.$('RoomInfo.bg.bg_top.battery');
                if (cc.sys.isObjectValid(battery)) {
                    var level = DeviceUtil.getBatteryLevel();
                    if (cc.sys.isObjectValid(battery)) {
                        if (level > 75) {
                            battery.setTexture(zipai.res.battery_5);
                        } else if (level > 50) {
                            battery.setTexture(zipai.res.battery_4);
                        } else if (level > 25) {
                            battery.setTexture(zipai.res.battery_3);
                        } else if (level > 10) {
                            battery.setTexture(zipai.res.battery_2);
                        } else {
                            battery.setTexture(zipai.res.battery_1);
                        }
                    }
                }
                var date = new Date();
                var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
                var hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
                if (cc.sys.isObjectValid(lbTime))
                    lbTime.setString(hours + (flag ? ':' : ' ') + minutes);
                else if (interval)
                    clearInterval(interval);
                flag = !flag;
            };
            updTime();
            interval = setInterval(updTime, 1000);
        },
        /**
         * 游戏信号显示
         */
        startSignal: function () {
            var that = this;
            var interval = null;
            var lastDealy = -1;
            var signal = that.$('RoomInfo.bg.bg_top.signal');
            var func = function () {
                if (!that || !cc.sys.isObjectValid(signal))
                    return clearInterval(interval);
                var delay = network.getLastPingInterval();
                if (delay == lastDealy)
                    return;
                lastDealy = delay;
                if (delay < 100) signal.setTexture(zipai.res.signal5);
                else if (delay < 200) signal.setTexture(zipai.res.signal4);
                else if (delay < 300) signal.setTexture(zipai.res.signal3);
                else if (delay < 600) signal.setTexture(zipai.res.signal2);
                else signal.setTexture(zipai.res.signal1);
            };
            func();
            interval = setInterval(func, 200);
        },
        /**
         * 设置庄家
         */
        setZhuang: function () {
            var self = this;
            for (var i = 0; i < this.zipaiManager.PlayerInfos.length; i++) {
                var uid = this.zipaiManager.PlayerInfos[i]['ID'];
                var row = this.zipaiManager.g_uid_to_pos[uid];
                var infoNode = self.$('info' + row, self.PlayerInfoNode);
                if (infoNode) {
                    infoNode.getChildByName('zhuang').setVisible(uid == this.zipaiManager.BankerUserID);
                }
            }
        },
        /**
         * 展示开局动画
         */
        setUpGameStartAnimation: function () {
            var self = this;
            //添加开局动画
            var showAnimation = function (pNode, aniName, isloop) {
                if (!cc.sys.isObjectValid(pNode) || aniName == '') {
                    return;
                }
                pNode.removeAllChildren();
                pNode.setOpacity(255);

                var tmpNode = pNode;
                var spineAni = playSpine(zipai.res.sp_kaiju_json, aniName, isloop, function (){
                    setTimeout(function () {
                        tmpNode.removeAllChildren();
                        tmpNode.setOpacity(0);
                    }, 2000);
                });
                pNode.addChild(spineAni);
                pNode.setScale(1.2, 1.2);
            };
            showAnimation(self.$('centerPos'), "kaiju", false);
        },
        /**
         * 游戏开始
         */
        setUpGameStart: function () {
            var self = this;
            this.setZhuang();
            this.setRoomState();
            self.$('FunctionBtn.bottomCenter.btn_invite').setVisible(false);
            self.$('FunctionBtn.bottomCenter.btn_tuichu').setVisible(false);
            self.$('FunctionBtn.bottomCenter.img_dengdaijiaru').setVisible(false);
            self.$('FunctionBtn.bottomCenter.btn_jiesan').setVisible(false);
            self.$('FunctionBtn.btn_copy').setVisible(false);
            self.$('FunctionBtn.bottomCenter.btn_zhunbei').setVisible(false);
            var cardsNode = self.$('PlayerInfo.node_wang');
            if(cardsNode){
                cardsNode.removeAllChildren();
            }
            //self.$('FunctionBtn.btn_mic').setVisible(true);
            //self.$('FunctionBtn.btn_chat').setVisible(true);
            this.playNextJu();
        },
        /**
         * 局数动画
         */
        playNextJu: function () {
            var self = this;
            var nextju = new cc.Sprite(res.nextju_png);
            nextju.setPosition(cc.p(DesignSize.width / 2, 350));
            this.getRootNode().addChild(nextju);
            var ju = new cc.LabelBMFont('', res.jushu_fnt);
            ju.setScale(1.3);
            ju.setPosition(cc.p(353 / 2, 78 / 2));
            ju.setString(this.zipaiManager.CurRound);
            nextju.addChild(ju);
            nextju.setScale(0);
            nextju.runAction(cc.sequence(
                cc.scaleTo(0.2, 0.8, 1.2),
                cc.scaleTo(0.16, 1.1, 0.9),
                cc.scaleTo(0.1, 0.95, 1.05),
                cc.scaleTo(0.1, 1, 1),
                cc.spawn(cc.moveTo(0.4, cc.p(DesignSize.width / 2, self.txtRound.getPositionY() + 10)), cc.scaleTo(0.4, 0)),
                cc.removeSelf()
            ));
        },
        getCardsNode: function (row) {
            return this.$('nCards' + row, this.PosNode);
        },
        /**
         * @returns OpenCards
         */
        getOpenNode: function (row) {
            return this.$('open' + row, this.PosNode).getChildByName('OpenCards');
        },
        /**
         * @returns OutCards
         */
        getOutNode: function (row) {
            cc.log('row===='+row)
            return this.$('out' + row, this.PosNode).getChildByName('OutCards');
        },
        /**
         * 设置胡息
         * @param row
         */
        setUpHX: function (row) {
            var self = this;
            var infoNode = self.$('info' + row, self.PlayerInfoNode);
            var txt = infoNode.getChildByName('txtHX');
            var txt_str = infoNode.getChildByName('txtHX_value');
            var showHx = mAction.showHx?mAction.showHx[row]:0;
            if (row == 0) {
                showHx += this.zipaiManager.getHandshuxi();
            }
            txt.setString('胡息');
            if (showHx == 0){
                txt_str.setString('');
            }
            else {
                txt_str.setString(showHx + '胡息');
            }

            // txt.setString('胡息:' + showHx);
        },
        /**
         * 切换牌面
         */
        changeCardSize: function () {
            settingData.hz_pai = (settingData.hz_pai + 1) % 3;
            cc.log(settingData.hz_pai);
            this.setCardFont();

        },
        changePai: function () {
            this.setCardFont();
        },
        //更换字体
        setCardFont: function () {
            for (var i = 0; i < this.zipaiManager.PlayersNum; i++) {
                var open = this.getOpenNode(i);
                var openChileren = open.getChildren();
                for (var j = 0; j < openChileren.length; j++) {
                    openChileren[j].resetCardImg();
                }
                var out = this.getOutNode(i);
                var outChileren = out.getChildren();
                for (j = 0; j < outChileren.length; j++) {
                    outChileren[j].resetCardImg();
                }
            }
            var mycards = this.getCardsNode(0).getChildren();
            for (j = 0; j < mycards.length; j++) {
                mycards[j].resetCardImg();
            }
            this.setUpCards();
        },
        /**
         * 刷新手牌
         */
        resetCards: function () {
            this._needShowTingTip = true;
            this.setUpCards();
        },
        setUpCardsHuXi: function () {
            var CardsNode = this.getCardsNode(0);
            this.cardScale = mCard.getCardScale();
            this.cardSize = mCard.getCardSize();
            var cardList = this.zipaiManager.CardList;

            if (!this.HuXiNode) {
                this.HuXiNode = new cc.Node();
                CardsNode.getParent().addChild(this.HuXiNode);
                this.HuXiNode.setPosition(CardsNode.getPosition());
            }
            this.HuXiNode.removeAllChildren();

            for (var i = 0; i < cardList.length; i++) {
                var posx = i * (this.cardSize.w * this.cardScale - 2) - this.cardSize.w / 2;

                var cards = deepCopy(cardList[i]);
                var typ = mCard.getComboType(cards, true);
                var huxi = mCard.getComboHuXi({cards: cards, typ: typ});
                var huxiBg = new cc.Sprite(zipai.res.huxiBg);
                huxiBg.setAnchorPoint(0.5, 0.5);
                huxiBg.setPosition(cc.p(posx, -50));
                this.HuXiNode.addChild(huxiBg);

                var txt = new cc.LabelBMFont(huxi + '胡息', zipai.res.huxi_fnt);
                txt.setAnchorPoint(0.5, 0.5);
                txt.setPosition(cc.p(posx, -50));
                this.HuXiNode.addChild(txt);
            }
            this.HuXiNode.setPositionX(DesignSize.width * 0.5 - cardList.length * 0.5 * this.cardSize.w * this.cardScale + this.cardSize.w);
            this.setUpHX(0);
            this.HuXiNode.setVisible(settingData.showhuxi);
        },
        hideCardsHuXi: function () {
            if (this.HuXiNode) {
                this.HuXiNode.removeAllChildren();
            }
        },
        /**
         * 设置自己的手牌
         */
        setUpCards: function () {
            var that = this;
            that.isMoving = true;
            that.isBeginTouch = true;
            var cardsNode = this.getCardsNode(0);
            cardsNode.setVisible(true);
            cardsNode.removeAllChildren();
            cardsNode.setScale(1);
            this.hideOk();
            this.setUpHX(0);
            this.cardScale = mCard.getCardScale();
            this.cardSize = mCard.getCardSize();
            var cardList = this.zipaiManager.CardList;

            for (var i = 0; i < cardList.length; i++) {
                var cards = cardList[i];
                var isKan = false;
                //坎 不能移动
                if ((cards.length == 3 || cards.length == 4) && cards[0] == cards[1] && cards[1] == cards[2] && cards[0] != 21) {
                    isKan = this.zipaiManager.isDaiKan;
                }
                for (var j = cards.length - 1; j >= 0; j--) {
                    var card = new Card();
                    cardsNode.addChild(card);
                    card.setData(cards[j], this);
                    card.setRowColumn(j, i);
                    card.setKan(isKan);
                    card.setLocalZOrder(3 - j);
                    card.setScale(this.cardScale);
                    var posx = i * (this.cardSize.w * this.cardScale - 2) - this.cardSize.w / 2;
                    var is4Same = cards.length == 4 && cards[0] == cards[1] && cards[0] == cards[2] &&
                        cards[0] == cards[3] && cards[0] != 21;
                    var posy = j * (this.cardSize.h * this.cardScale - (is4Same ? 45 : 35)) - 30;
                    if(that.isPaiOffSetY){
                        posy -= mCard.getCardOffsetY();
                    }
                    card.setPosition(posx, posy);
                    var tag = (i + 1) * 100 + j + 1;
                    card.setTag(tag);
                }
            }
            that.setUpCardsHuXi();
            that.setLeftCard();
            that.$('FunctionBtn.btn_refresh').setVisible(cardList.length > 0 && this.isBaiPai);
            //冻结
            this.setFreezeCard();
            cardsNode.setPositionX(DesignSize.width  * 0.5 - cardList.length * 0.5 * this.cardSize.w * this.cardScale + this.cardSize.w);
            //重新设置
            that.scheduleOnce(function () {
                that.isMoving = false;
                that.isBeginTouch = false;
            }, 0.5);

            //如果有听牌提示且需要重新显示听，则调显示听
            if (that._needShowTingTip) {
                that.setTishiList();
                that._needShowTingTip = false;
            }
            // if (this.zipaiManager.Sipai) {
            //     var CardsNode = this.getCardsNode(2);
            //     CardsNode.setVisible(true);
            //     CardsNode.removeAllChildren();
            //     CardsNode.setScale(1);
            //     var Sipaicnt = this.zipaiManager.Sipaicnt;
            //     var count = parseInt(Sipaicnt / 3);
            //     var yushu = Sipaicnt % 3;
            //     var cardList = [];
            //     var yuList = [];
            //     for (var k = 0; k < count; k++) {
            //         cardList.push([0, 0, 0]);
            //     }
            //     for (var k = 0; k < yushu; k++) {
            //         yuList.push(0);
            //     }
            //     cardList.push(yuList);
            //     for (var i = 0; i < cardList.length; i++) {
            //         var cards = cardList[i];
            //         for (var j = cards.length - 1; j >= 0; j--) {
            //             var card = new Card();
            //             CardsNode.addChild(card);
            //             card.setData(cards[j], this, 2);
            //             card.setTouchEnableStatus(false);
            //             card.setPosition(i * 42, (j - 1) * 42);
            //             var tag = (i + 1) * 100 + j + 1;
            //             card.setTag(tag);
            //         }
            //     }
            // }
        },
        /**
         * 设置其他人的手牌
         */
        setUpOtherCards: function (id) {
            if (id >= this.playersNum) {
                if (!this.zipaiManager.Sipai)
                    return;
                else {
                    this.getOpenNode(2).setVisible(false);
                }
            }
            var CardsNode = this.getCardsNode(id);
            if (!CardsNode)
                return;
            this.cardScale = mCard.getCardScale();
            this.cardSize = mCard.getCardSize();
            CardsNode.setVisible(true);
            CardsNode.removeAllChildren();
            CardsNode.setScale(0.5);
            var cardList = this.zipaiManager['CardList' + id];
            if (cardList == undefined || cardList == null) {
                return;
            }
            for (var i = 0; i < cardList.length; i++) {
                var cards = cardList[i];
                for (var j = cards.length - 1; j >= 0; j--) {
                    var card = new Card();
                    CardsNode.addChild(card);
                    card.setData(cards[j], this);
                    card.setTouchEnableStatus(false);
                    card.setPosition(i * this.cardSize.w, j * this.cardSize.h - 80);
                    var tag = (i + 1) * 100 + j + 1;
                    card.setTag(tag);
                }
            }
        },
        /**
         * 回放直接结束
         */
        resetPlayerCards: function (round) {
            this.clearRoom();
            var playerscards = this.zipaiManager.roomReplayDate.getAllPlayerCardsByStep(round);
            for (var id in playerscards) {
                if (playerscards.hasOwnProperty(id)) {
                    var playercard = playerscards[id];
                    var pos = this.zipaiManager.g_uid_to_pos[id];
                    var outCards = this.getOutNode(pos);//room['out' + pos];
                    var openCards = this.getOpenNode(pos);//room['open' + pos];
                    if (this.zipaiManager.shouxing && mRoom.sxUserId > 0) {
                        if (pos == 3)
                            continue;
                    }
                    if (pos == 0) {
                        this.zipaiManager.setSeverCardList(playercard.cards);
                        this.zipaiManager.setCardList();
                        this.setUpCards();
                    } else {
                        this.zipaiManager.setOtherCardList(playercard.cards, pos);
                        this.setUpOtherCards(pos);
                    }
                    for (var j = 0; j < playercard.out.length; j++) {
                        var card = playercard.out[j];
                        outCards.addCard(card);
                    }
                    for (j = 0; j < playercard.open.length; j++) {
                        openCards.addCards(playercard.open[j].cards, playercard.open[j].typ, false);
                    }
                    //设置胡息
                    this.setUpHX(pos);
                    this.zipaiManager.setLeftCardCount(mAction.leftCardCount);
                    this.setLeftCard();
                }
            }
        },
        chuPai: function (card) {
            var self = this;
            network.sendPhz(5000, 'ShowCard/' + card + '/' + self.outSeq);
        },
        userShowCard: function (card, isAuto, row, column, target, position) {
            var self = this;
            this.outCardRow = row + 1;
            this.outCardColumn = column + 1;

            //明偎  射跑的判断
            if (ZiPaiRoomData.options.mingwei) {
                var isShepao = false;
                for (var i = 1; i <= this.zipaiManager.PlayersNum; i++) {
                    if (mAction.combos[i] && mAction.combos[i].length > 0) {
                        for (var j = 0; j < mAction.combos[i].length; j++) {
                            if ((mAction.combos[i][j].typ == mCard.comboTypes.chouwei
                                || mAction.combos[i][j].typ == mCard.comboTypes.wei)
                                && parseInt(mAction.combos[i][j].cards[0]) == parseInt(card)) {
                                isShepao = true;
                                self._isShePao = true;
                                break;
                            }
                        }
                    }
                }
                if (isShepao) {
                    showMessageBox('射跑，之后您将无法吃、碰，请问是否出牌?', function () {
                        self.chuPai(card);
                        self.tipLine.setVisible(false);
                        self._isShePao = null;
                        //点击确定后，需将isTurnOut的标记置为false，如果有手指滑动动画，也需隐藏。
                        self.isTurnOut = false;
                        self.fingerAni(false);
                    }, function () {
                        self.movecard = target;
                        // cc.log('----------------A: isShepao' + movecard.data);
                        self.positionBak = position;
                        if (self.movecard) {
                            self._needShowTingTip = true;
                            self.movecard.setPosition(self.positionBak);
                            self.setUpCards();
                            self.setSameCardShow(self.movecard.data, false);
                        }
                        self.movecard = null;
                        self.positionBak = null;
                        self._isShePao = null;
                    });
                    return;
                }
            }
            //耒阳玩法  有234 吃了别人的5，出2时，提示
            if (ZiPaiRoomData.options.Chibian) {
                if (self.Notice && self.Notice.length > 0 && self.Notice.indexOf(card) >= 0) {
                    showMessageBox('吃边打边，本局只能胡红胡、黑胡、点朱和无胡，确定出牌吗?', function () {
                        self.chuPai(card);
                        self.tipLine.setVisible(false);
                        self._isShePao = null;
                        self.Notice = null;
                        //点击确定后，需将isTurnOut的标记置为false，如果有手指滑动动画，也需隐藏。
                        self.isTurnOut = false;
                        self.fingerAni(false);
                    }, function () {
                        self.movecard = target;
                        self.positionBak = position;

                        if (self.movecard) {
                            self._needShowTingTip = true;
                            self.movecard.setPosition(self.positionBak || cc.p(0, 0));
                            self.setUpCards();
                            self.setSameCardShow(self.movecard.data, false);
                        }
                        self.movecard = null;
                        self.positionBak = null;
                        self._isShePao = null;
                    });
                    return;
                }
            }
            if (isAuto == true) {
                self.scheduleOnce(function () {
                    self.fingerAni(false);
                    self.chuPai(card);
                    self.tipLine.setVisible(false);
                }, 1);
            } else {
                self.fingerAni(false);
                self.chuPai(card);
                self.tipLine.setVisible(false);
            }
            self.setTurnOutOver();
            if (self.outSeq == null) {
                cc.log('outSeq is null');
            }
        },
        setTurnOutOver: function () {
            this.isTurnOut = false;
            this.secondsLeft = 0;
            this.zipaiManager.TishiList = null;
        },
        touchTingPai:function (paiId) {
            var self = this;
            var tishiData = self.zipaiManager.TishiList;
            if (tishiData && tishiData.length > 0) {
                for (var k = 0; k < tishiData.length; k++) {
                    if (tishiData[k]['Card'] == paiId) {
                        self.showTingPaiOnDesk(tishiData[k]['TingCards'], 'touchMove');
                        break;
                    }
                }
            }
        },
        /**
         * 显示听牌数据
         * @param data
         * @param type
         */
        showTingPaiOnDesk: function (data, type) {
            var ting_pos = this.tingNode.getChildByName('ting_pos');
            var tingBg = this.tingNode.getChildByName('tingBg');
            this.tingNode.setVisible(false);
            ting_pos.removeAllChildren();
            if (!data || data.length == 0)
                return;
            var _len = data.length;
            for (var i = 0; i < _len; i++) {
                var tingCardInfo = data[i];
                var card = new Card();
                card.setData(tingCardInfo['Card'], null, 2);
                card.setAnchorPoint(0, 0.5);
                card.setPosition(i * 70, 1);
                ting_pos.addChild(card);

                var num = new ccui.Text();
                num.setString(tingCardInfo['Left']);
                num.setFontSize(20);
                num.setAnchorPoint(cc.p(0, 0.5));
                num.setPosition(cc.p(48 + i * 70, 0));
                num.setColor(cc.color(255, 255, 255));
                ting_pos.addChild(num);
            }
            if (_len > 0) {
                tingBg.setContentSize(cc.size(70 + _len * 70, tingBg.getContentSize().height));
                this.tingNode.setVisible(true);
            } else {
                this.tingNode.setVisible(false);
            }
        },
        /**
         * 胡牌提示
         */
        setTingPaiList: function () {
            this.showTingPaiOnDesk(this.zipaiManager.TingCards);
            var handList = this.getCardsNode(0).getChildren();
            for (var i = 0; i < handList.length; i++) {
                var card = handList[i];
                card.setTingMark(false);
            }
        },
        /**
         * 听牌提示
         */
        setTishiList: function () {
            this.showTingPaiOnDesk(this.zipaiManager.TingCards);
            var tishiData = this.zipaiManager.TishiList; //
            if (tishiData) {
                var handList = this.getCardsNode(0).getChildren();
                for (var i = 0; i < handList.length; i++) {
                    var card = handList[i];
                    for (var j = 0; j < tishiData.length; j++) {
                        if (card.data == tishiData[j]['Card'])
                            card.setTingMark(true);
                    }
                }
            }
        },
        /**
         * 清理听牌
         */
        clearTingPai: function () {
            var handList = this.getCardsNode(0).getChildren();
            for (var i = 0; i < handList.length; i++) {
                var card = handList[i];
                card.setTingMark(false);
            }
            this.tingNode.setVisible(false);
        },
        /**
         * 添加牌触摸
         */
        enableChuPai: function () {
            var self = this;
            var touchLayer = this.getChildByName('touchLayer');
            if (touchLayer) return;
            self._isShePao = false;

            touchLayer = new cc.LayerColor(cc.color(0, 0, 0, 0), cc.winSize.width, cc.winSize.height);
            touchLayer.setName('touchLayer');
            touchLayer.setAnchorPoint(0, 0);
            self.addChild(touchLayer);

            self.isMoving = false;
            self.isBeginTouch = false;  //禁止多点触控 禁止俩手同时点击 同时移动两张牌
            var firstCardPos = cc.p(0, 0);
            var chupaiListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ONE_BY_ONE,
                swallowTouches: true,
                onTouchBegan: function (touch, event) {
                    try {
                        if (self.movecard && self.positionBak && (self.isBeginTouch)) {
                            if (self.movetocardArr && self.movetocardArr.length > 0) {
                                for (var n = 0; n < self.movetocardArr.length; n++) {
                                    self.movetocardArr[n].stopAllActions();
                                    self.movetocardArr[n].runAction(cc.sequence(
                                        cc.moveTo(0.1, self.movetocardPosArr[n])
                                    ));
                                }
                            }
                            self.movetocardArr = [];
                            self.movetocardPosArr = [];

                            if (self.zorderBak) self.movecard.setLocalZOrder(self.zorderBak);
                            self.movecardTmp.setVisible(false);
                            self.movecard.stopAllActions();
                            self.movecard.setPosition(self.movecardTmp.getPosition());
                            self.movecard.setOpacity(255);
                            self.movecard.runAction(cc.sequence(
                                cc.moveTo(0.1, self.positionBak),
                                cc.callFunc(function (sender) {
                                    self.isMoving = false;
                                    self.isBeginTouch = false;
                                    sender = null;
                                })
                            ));
                            return;
                        }
                        if (self.isBeginTouch) {
                            return;
                        }
                        var nCards0 = self.getCardsNode(0);
                        var cardList = deepCopy(self.zipaiManager.CardList);
                        if (nCards0.getChildByTag(101)) firstCardPos = nCards0.getChildByTag(101).getPosition();
                        self.cardsXYBak = [];
                        for (var i = 0; i < cardList.length; i++) {
                            if (self.cardsXYBak[i] == null) self.cardsXYBak[i] = [];
                            for (var j = 0; j < cardList[i].length; j++) {
                                if (self.cardsXYBak[i][j] == null) self.cardsXYBak[i][j] = {};
                                self.cardsXYBak[i][j] = {card: cardList[i][j], x: i, y: j, tag: (i + 1) * 100 + j + 1};
                            }
                        }
                        var cardSprites = nCards0.getChildren();
                        for (i = 0; i < cardSprites.length; i++) {
                            if (TouchUtil.isTouchMe(cardSprites[i], touch, event, null, mCard.getouchRect())) {
                                self.movecard = cardSprites[i];
                                self.movexy = {x: self.movecard.column, y: self.movecard.row};
                                //坎不能出
                                if (self.zipaiManager.isDaiKan && cardList && cardList[self.movecard.column] &&
                                    // that.cardList[movecard.column].length == 3 &&
                                    cardList[self.movecard.column][0] == cardList[self.movecard.column][1] &&
                                    cardList[self.movecard.column][0] == cardList[self.movecard.column][2] &&
                                    cardList[self.movecard.column][0] != 21) {
                                    if (self.movexy.y < 4) {
                                        self.movecard = null;
                                        self.movexy = null;
                                        return false;
                                    }
                                }
                                self.zorderBak = self.movecard.getLocalZOrder();
                                self.positionBak = self.movecard.getPosition();
                                self.movecard.setOpacity(0);
                                self.movecardTmp = nCards0.getChildByName('movecardTmp');
                                if (self.movecardTmp == null || self.movecardTmp == undefined) {
                                    self.movecardTmp = new Card();
                                    self.movecardTmp.setName('movecardTmp');
                                    nCards0.addChild(self.movecardTmp);
                                }
                                self.movecardTmp.setLocalZOrder(10);
                                self.movecardTmp.setData(self.movecard.data, null, 0);
                                self.movecardTmp.setVisible(true);
                                self.movecardTmp.setRowColumn(self.movecard.row, self.movecard.column);
                                self.movecardTmp.setPosition(self.movecard.getPosition());
                                if (self.movecard.getChildByName('tingmark') && cc.sys.isObjectValid(self.movecard.getChildByName('tingmark'))
                                    && self.movecard.getChildByName('tingmark').isVisible()) {
                                    self.movecardTmp.setTingMark(true);
                                    self.movecard.getChildByName('tingmark').setOpacity(0);
                                }
                                self.setSameCardShow(self.movecard.data, true);//选中相同颜色的
                                self.isBeginTouch = true;
                                self.touchTingPai(self.movecard.data);
                                return true;
                            }
                        }
                        return false;
                    } catch (e) {
                        network.sendPhz(5000, 'CheckHand/' + 'onTouchBegan' + '/movingError/' + e.toString());
                        showAlert('e : ' + e.toString());
                    }
                },
                onTouchMoved: function (touch, event) {
                    try {
                        if (self.movecard && cc.sys.isObjectValid(self.movecard)) {
                            var p = self.movecardTmp.convertToNodeSpace(touch.getLocation());
                            p.x += self.movecardTmp.getPositionX() - self.movecardTmp.getBoundingBox().width / 2;
                            p.y += self.movecardTmp.getPositionY() - self.movecardTmp.getBoundingBox().height / 2;
                            self.movecardTmp.setPosition(p);
                            if (p.y > self.CHUPAI_HEIGHT) {
                                return;
                            }
                            var isMove = false;
                            var nCards0 = self.getCardsNode(0);
                            var cardList = deepCopy(self.zipaiManager.CardList);
                            //先判断是不是移动到最左边  或者最右边  数组需要新建一列
                            var firsrCard = nCards0.getChildByTag(101);
                            var lastCard = nCards0.getChildByTag(cardList.length * 100 + 1);
                            if (firsrCard && cardList.length < zipai.curBaipaiLength &&
                                (self.movecardTmp.getPositionX() + self.movecardTmp.getBoundingBox().width / 2) < firsrCard.getPositionX()) {
                                //移到最左边
                                isMove = true;
                                self.movetoxy = {x: 0, add: 'left', y: 0};
                                // console.log("移到最左边");
                            }
                            if (isMove == false && lastCard && cardList.length < zipai.curBaipaiLength &&
                                (self.movecardTmp.getPositionX() + self.movecardTmp.getBoundingBox().width / 2) > lastCard.getPositionX() + lastCard.getBoundingBox().width) {
                                //移到最右边
                                isMove = true;
                                self.movetoxy = {x: cardList.length, add: 'right', y: 0};
                                // console.log("移到最右边");
                            }
                            if (isMove == false) {
                                var cardSprites = nCards0.getChildren();
                                for (var i = 0; i < cardSprites.length; i++) {
                                    var cardi = cardSprites[i];
                                    var moveCardMidX = self.movecardTmp.getPositionX() + self.movecardTmp.getBoundingBox().width / 2;
                                    var moveCardMidY = self.movecardTmp.getPositionY() + self.movecardTmp.getBoundingBox().height / 2;
                                    var cardiL = cardi.getPositionX() - cardi.getBoundingBox().width * 0.05;
                                    var cardiL2 = cardi.getPositionX() - cardi.getBoundingBox().width * 0.25;
                                    var cardiR = cardi.getPositionX() + cardi.getBoundingBox().width * 1.05;
                                    var cardiT = cardi.getPositionY() + cardi.getBoundingBox().height * 1;
                                    var cardiD = cardi.getPositionY();
                                    if (self.movecard.column == cardi.column && self.movecard.row == cardi.row) {
                                    } else {
                                        if (moveCardMidX >= cardiL && moveCardMidX <= cardiR) {
                                            var cardColunmTopRow = null;
                                            for (var s = 3; s >= 0; s--) {
                                                if (nCards0.getChildByTag(((cardi.column + 1) * 100) + s)) {
                                                    cardColunmTopRow = nCards0.getChildByTag(((cardi.column + 1) * 100) + s);
                                                    break;
                                                }
                                            }
                                            isMove = true;
                                            if (TouchUtil.isTouchMe(cardi, touch, event, null, mCard.getouchRect())) {
                                                if ((cardi.column == self.movexy.x && cardList[cardi.column].length <= self.MAXROW)
                                                    || (cardi.column != self.movexy.x && cardList[cardi.column].length < self.MAXROW)) {
                                                    self.movetoxy = {x: cardi.column, y: cardi.row, add: 'false'};
                                                    //强制改一下  todo spring
                                                    // console.log("spring1");
                                                    if (self.movetoxy.y >= cardList[self.movetoxy.x].length) self.movetoxy.y = cardList[self.movetoxy.x].length - 1;
                                                    if (self.movetoxy.y < 0) self.movetoxy.y = 0;
                                                    if (self.movetoxy.y >= self.MAXROW) self.movetoxy.y = self.MAXROW - 1;
                                                    break;
                                                }
                                            } else if (cardColunmTopRow && cardList[cardi.column].length < self.MAXROW &&
                                                moveCardMidY >= (cardColunmTopRow.getPositionY() + cardColunmTopRow.getBoundingBox().height)) {
                                                self.movetoxy = {
                                                    x: cardi.column,
                                                    y: ((cardi.column == self.movexy.x) ? (cardList[cardi.column].length - 1)
                                                        : (cardList[cardi.column].length)), add: 'false'
                                                };
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            //不能移动到坎上
                            if (self.movetoxy && cardList && cardList[self.movetoxy.x] &&
                                // that.cardList[movetoxy.x].length == 3 &&
                                cardList[self.movetoxy.x][0] == cardList[self.movetoxy.x][1] &&
                                cardList[self.movetoxy.x][0] == cardList[self.movetoxy.x][2]) {
                                if (self.movetoxy.y < 4 && self.movetoxy.add == 'false') {
                                    isMove = false;
                                }
                            }
                            if (isMove == false) self.movetoxy = null;
                            //如果不是相同列移动， 移到能够到得列数量大于4，则不移动
                            if (self.movetoxy && self.movetoxy.x != self.movexy.x && cardList[self.movetoxy.x] && cardList[self.movetoxy.x].length >= self.MAXROW) {
                                isMove = false;
                            }
                            if (self.movetoxy && self.movetoxy.x == self.movexy.x && self.movetoxy.y == self.movexy.y) {
                                return;
                            }
                            // console.log(movetoxy);
                            if (self.movetoxy && self.movecard) {
                                if (((self.movetoxy.add == 'mid' && self.movetoxy.x > self.movexy.x) || self.movetoxy.add == 'right') && cardList[self.movexy.x].length == 1) {
                                    self.movetoxy.x = self.movetoxy.x - 1;
                                }
                                self.isMoving = true;
                                // console.log(movetoxy);
                                // console.log(movetoxybak);
                                if (self.movetoxybak && (self.movetoxybak.x == self.movetoxy.x && self.movetoxybak.y == self.movetoxy.y && self.movetoxybak.add == self.movetoxy.add)) {
                                    // console.log("移动的一样");
                                    self.isMoving = false;
                                    return;
                                }
                                for (var s = 0; s < self.movetocardArr.length; s++) {
                                    var card = self.movetocardArr[s];
                                    if (card && cc.sys.isObjectValid(card)) {
                                        card.stopAllActions();
                                        card.setPosition(self.movetocardPosArr[s]);
                                    }
                                }
                                self.movetocardArr = [];
                                self.movetocardPosArr = [];

                                // console.log("开始移动");
                                self.movetoxybak = deepCopy(self.movetoxy);
                                // console.log(movetoxy);
                                // console.log(movexy);
                                if (self.movetoxy.add != 'false') {
                                    //新加一列
                                    self.movecard.stopAllActions();
                                    self.movecard.runAction(cc.sequence(
                                        cc.delayTime(0.1),
                                        cc.callFunc(function () {
                                            self.isMoving = false;
                                        })
                                    ));
                                } else {
                                    var cardSize = mCard.getCardSize();
                                    var cardScale = mCard.getCardScale();
                                    if (self.movexy.x == self.movetoxy.x) {
                                        var card = nCards0.getChildByTag(100 * (self.movetoxy.x + 1) + self.movetoxy.y + 1);
                                        if (card) {
                                            self.movetocardArr[0] = card;
                                            self.movetocardPosArr[0] = card.getPosition();
                                            card.stopAllActions();
                                            card.runAction(cc.sequence(
                                                cc.moveBy(0.1, cc.p(0, (self.movexy.y - self.movetoxy.y) * (cardSize.h * cardScale - 35))),
                                                cc.callFunc(function () {
                                                    self.isMoving = false;
                                                })
                                            ));
                                        }
                                    } else {
                                        for (var n = self.movetoxy.y; n < 4; n++) {
                                            var nlength = self.movetocardArr.length;
                                            var card = nCards0.getChildByTag(100 * (self.movetoxy.x + 1) + n + 1);
                                            if (card) {
                                                self.movetocardArr[nlength] = card;
                                                self.movetocardPosArr[nlength] = card.getPosition();
                                            }
                                        }
                                        if (self.movetocardArr.length == 0) {
                                            self.movecard.stopAllActions();
                                            self.movecard.runAction(cc.sequence(
                                                cc.delayTime(0.2),
                                                cc.callFunc(function () {
                                                    self.isMoving = false;
                                                })
                                            ));
                                        } else {
                                            if (self.movetocardArr && self.movetocardArr.length > 0) {
                                                for (var n = 0; n < self.movetocardArr.length; n++) {
                                                    self.movetocardArr[n].stopAllActions();
                                                    self.movetocardArr[n].runAction(cc.sequence(
                                                        cc.moveBy(0.1, cc.p(0, (cardSize.h * cardScale - 35))),
                                                        cc.callFunc(function () {
                                                            self.isMoving = false;
                                                            // console.log("当前列加一个数据" + isMoving);
                                                        })
                                                    ));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (e) {
                        network.sendPhz(5000, 'CheckHand/' + 'onTouchMoved' + '/movingError/' + e.toString());
                        showAlert('e : ' + e.toString());
                    }
                },
                onTouchEnded: function (touch, event) {
                    try {
                        self.showTingPaiOnDesk(self.zipaiManager.TingCards);
                        var nCards0 = self.getCardsNode(0);
                        var cardList = deepCopy(self.zipaiManager.CardList);
                        var cardSize = mCard.getCardSize();
                        var cardScale = mCard.getCardScale();
                        if (ZiPaiRoomData.options.shouxing && mRoom.sxUserId > 0) {
                            if (self.movecardTmp && cc.sys.isObjectValid(self.movecardTmp)
                                && self.movecardTmp.getPositionY() >= (self.CHUPAI_HEIGHT - self.movecardTmp.getContentSize().height / 2 - 20)
                                && self.movecardTmp.data != 21 && gameData.uid != mRoom.sxUserId) {
                                if (self.isTurnOut == true && !self.nAction.isVisible()) {
                                    self.userShowCard(self.movecardTmp.data, false, self.movecardTmp.row, self.movecardTmp.column);
                                    self.setSameCardShow(self.movecardTmp.data, false);//选中相同颜色的
                                    self.movexy = null;
                                    self.movetoxy = null;
                                    self.movetoxybak = null;
                                    self.movecard = null;
                                    self.positionBak = null;
                                    return;
                                }
                            }
                        } else {
                            if (self.movecardTmp && cc.sys.isObjectValid(self.movecardTmp)
                                && self.movecardTmp.getPositionY() >= (self.CHUPAI_HEIGHT - self.movecardTmp.getContentSize().height / 2 - 20)
                                && self.movecardTmp.data != 21) {
                                if (self.isTurnOut == true && !self.nAction.isVisible() && !self.isFreeze(self.movecardTmp.data)) {
                                    self.setSameCardShow(self.movecardTmp.data, false);//选中相同颜色的
                                    self.userShowCard(self.movecardTmp.data, false, self.movecardTmp.row, self.movecardTmp.column, self.movecard, self.positionBak);
                                    self.movexy = null;
                                    self.movetoxy = null;
                                    self.movetoxybak = null;
                                    if (!self._isShePao) {
                                        self.movecard = null;
                                        self.positionBak = null;
                                    }
                                    return;
                                }
                            }
                        }
                        if (self.movecard && cc.sys.isObjectValid(self.movecard) && !self._isShePao) {
                            if (self.movecardTmp && cc.sys.isObjectValid(self.movecardTmp) && self.movecardTmp.getPositionY() >= self.CHUPAI_HEIGHT) {
                                if (self.movetocardArr && self.movetocardArr.length > 0) {
                                    for (var n = 0; n < self.movetocardArr.length; n++) {
                                        self.movetocardArr[n].stopAllActions();
                                        self.movetocardArr[n].runAction(cc.sequence(
                                            cc.moveTo(0.1, self.movetocardPosArr[n])
                                        ));
                                    }
                                }
                                self.movetocardArr = [];
                                self.movetocardPosArr = [];

                                self.movecard.stopAllActions();
                                self.movecardTmp.setVisible(false);
                                self.movecard.setPosition(self.movecardTmp.getPosition());
                                self.movecard.setOpacity(255);
                                if (self.movecard.getChildByName('tingmark') && cc.sys.isObjectValid(self.movecard.getChildByName('tingmark'))
                                    && self.movecard.getChildByName('tingmark').isVisible()) {
                                    self.movecardTmp.setTingMark(false);
                                    self.movecard.getChildByName('tingmark').setOpacity(255);
                                }
                                self.movecard.setLocalZOrder(self.zorderBak);
                                self.movecard.runAction(cc.sequence(
                                    cc.moveTo(0.1, self.positionBak),
                                    cc.callFunc(function (sender) {
                                        self.setSameCardShow(self.movecard.data, false);//选中相同颜色的
                                        self.movexy = null;
                                        self.movetoxy = null;
                                        self.movetoxybak = null;
                                        self.movecard = null;
                                        self.positionBak = null;
                                        self.isBeginTouch = false;
                                        self.isMoving = false;
                                        cc.sys.localStorage.setItem('Storage_handsCards', JSON.stringify(cardList));
                                    })
                                ));
                                self.checkHandCards();
                                return;
                            }
                            var isMoveLineDelete = true;
                            if (cardList[self.movexy.x] && cardList[self.movexy.x].length > 1) isMoveLineDelete = false;
                            self.isMoving = false;
                            var cardSprites = nCards0.getChildren();
                            for (var s = 0; s < self.movetocardArr.length; s++) {
                                var card = self.movetocardArr[s];
                                if (card && cc.sys.isObjectValid(card)) {
                                    card.stopAllActions();
                                    card.runAction(cc.sequence(
                                        cc.moveTo(0.1, self.movetocardPosArr[s])
                                    ));
                                }
                            }
                            self.movetocardArr = [];
                            self.movetocardPosArr = [];
                            // //单击换牌
                            // if (self.movetoxy == null && self.movetoxybak == null && cardList[self.movexy.x] && cardList[self.movexy.x].length == 2) {
                            //     self.movetoxy = {x: self.movexy.x, y: (self.movexy.y == 1) ? 0 : 1, add: 'false'};
                            // }
                            if (self.movetoxy == null) {
                                if (self.movecard && self.movecard.data) {
                                    var cardno = self.movecard.data;
                                    self.movecardTmp.setVisible(false);
                                    self.movecard.setPosition(self.movecardTmp.getPosition());
                                    self.movecard.setOpacity(255);
                                    self.movecard.stopAllActions();

                                    if (self.movecard.getChildByName('tingmark') && cc.sys.isObjectValid(self.movecard.getChildByName('tingmark'))
                                        && self.movecard.getChildByName('tingmark').isVisible()) {
                                        self.movecardTmp.setTingMark(false);
                                        self.movecard.getChildByName('tingmark').setOpacity(255);
                                    }

                                    self.movecard.runAction(cc.sequence(
                                        cc.moveTo(0.1, cc.p(self.positionBak)),
                                        cc.callFunc(function (sender) {
                                            self.isBeginTouch = false;
                                        })
                                    ));
                                }
                                self.checkHandCards();
                            } else {
                                console.log("移动到====" + self.movetoxy.x + "===" + self.movetoxy.y + "====" + self.movetoxy.add);
                                if (self.movetoxy.add == 'left') {
                                    //移动到第一列
                                    var tmp = cardList[self.movexy.x][self.movexy.y];
                                    var xybaktmp = deepCopy(self.cardsXYBak[self.movexy.x][self.movexy.y]);
                                    if (cardList[self.movexy.x].length == 1) {
                                        cardList[self.movexy.x].splice(self.movexy.y, 1);
                                        self.cardsXYBak[self.movexy.x].splice(self.movexy.y, 1);
                                        for (var i = self.movexy.x; i > 0; i--) {
                                            cardList[i] = cardList[i - 1];
                                            self.cardsXYBak[i] = self.cardsXYBak[i - 1];
                                        }
                                        cardList[0] = [];
                                        self.cardsXYBak[0] = [];
                                        cardList[0].push(tmp);
                                        self.cardsXYBak[0].push(xybaktmp);
                                    } else {
                                        cardList[self.movexy.x].splice(self.movexy.y, 1);
                                        self.cardsXYBak[self.movexy.x].splice(self.movexy.y, 1);
                                        for (var i = cardList.length - 1; i >= 0; i--) {
                                            cardList[i + 1] = cardList[i];
                                            self.cardsXYBak[i + 1] = self.cardsXYBak[i];
                                        }
                                        cardList[0] = [];
                                        self.cardsXYBak[0] = [];
                                        cardList[0].push(tmp);
                                        self.cardsXYBak[0].push(xybaktmp);
                                    }
                                    // console.log(cardsXYBak);
                                } else if (self.movetoxy.add == 'right') {
                                    //移动到最后一列
                                    var tmp = cardList[self.movexy.x][self.movexy.y];
                                    var xybaktmp = deepCopy(self.cardsXYBak[self.movexy.x][self.movexy.y]);
                                    if (cardList[self.movexy.x].length == 1) {
                                        cardList[self.movexy.x].splice(self.movexy.y, 1);
                                        self.cardsXYBak[self.movexy.x].splice(self.movexy.y, 1);
                                        for (var i = self.movexy.x; i < cardList.length - 1; i++) {
                                            cardList[i] = cardList[i + 1];
                                            self.cardsXYBak[i] = self.cardsXYBak[i + 1];
                                        }
                                        cardList[cardList.length - 1] = [];
                                        self.cardsXYBak[self.cardsXYBak.length - 1] = [];
                                        cardList[cardList.length - 1].push(tmp);
                                        self.cardsXYBak[self.cardsXYBak.length - 1].push(xybaktmp);
                                    } else {
                                        cardList[self.movexy.x].splice(self.movexy.y, 1);
                                        self.cardsXYBak[self.movexy.x].splice(self.movexy.y, 1);
                                        var addNum = cardList.length;
                                        cardList[addNum] = [];
                                        self.cardsXYBak[addNum] = [];
                                        cardList[addNum].push(tmp);
                                        self.cardsXYBak[addNum].push(xybaktmp);
                                    }
                                } else {
                                    if (self.movetoxy.x == self.movexy.x) {
                                        //当前列交换数据
                                        if (cardList[self.movetoxy.x]) {
                                            var tmp = cardList[self.movexy.x][self.movexy.y];
                                            var xybaktmp = deepCopy(self.cardsXYBak[self.movexy.x][self.movexy.y]);
                                            cardList[self.movexy.x][self.movexy.y] = cardList[self.movetoxy.x][self.movetoxy.y];
                                            self.cardsXYBak[self.movexy.x][self.movexy.y] = self.cardsXYBak[self.movetoxy.x][self.movetoxy.y];
                                            cardList[self.movetoxy.x][self.movetoxy.y] = tmp;
                                            self.cardsXYBak[self.movetoxy.x][self.movetoxy.y] = xybaktmp;
                                        }
                                    } else {
                                        //别的列移动过来的
                                        if (cardList[self.movetoxy.x]) {
                                            var tmp = cardList[self.movexy.x][self.movexy.y];
                                            var xybaktmp = deepCopy(self.cardsXYBak[self.movexy.x][self.movexy.y]);
                                            cardList[self.movexy.x].splice(self.movexy.y, 1);
                                            self.cardsXYBak[self.movexy.x].splice(self.movexy.y, 1);
                                            //y 所有的网上移动
                                            for (var s = cardList[self.movetoxy.x].length - 1; s >= self.movetoxy.y; s--) {
                                                cardList[self.movetoxy.x][s + 1] = cardList[self.movetoxy.x][s];
                                                self.cardsXYBak[self.movetoxy.x][s + 1] = self.cardsXYBak[self.movetoxy.x][s];
                                            }
                                            cardList[self.movetoxy.x][self.movetoxy.y] = tmp;
                                            self.cardsXYBak[self.movetoxy.x][self.movetoxy.y] = xybaktmp;
                                        }
                                    }
                                }
                                //移除空的列
                                for (var i = 0; i < cardList.length; i++) {
                                    for (var j = cardList[i].length - 1; j >= 0; j--) {
                                        if (cardList[i][j] == null || cardList[i][j] == undefined) {
                                            cardList[i].splice(j, 1);
                                            self.cardsXYBak[i].splice(j, 1);
                                        }
                                    }
                                }
                                for (var i = 0; i < cardList.length; i++) {
                                    if ((cardList[i] == null || cardList[i] == undefined)
                                        || (cardList[i] && cardList[i].length == 0)) {
                                        cardList.splice(i, 1);
                                        self.cardsXYBak.splice(i, 1);
                                        break;
                                    }
                                }
                                //是否增加长度
                                var addCloumnNum = 0;
                                if (self.movetoxy.add == 'left' || self.movetoxy.add == 'right' || self.movetoxy.add == 'mid') {
                                    addCloumnNum = (isMoveLineDelete == false) ? 1 : 0;
                                } else {
                                    addCloumnNum = (isMoveLineDelete == false) ? 0 : -1;
                                }
                                if (addCloumnNum != 0) {
                                    firstCardPos.x = firstCardPos.x + ((addCloumnNum == -1) ? (cardSize.w * cardScale - 2) / 2 : -(cardSize.w * cardScale - 2) / 2);
                                }
                                // console.log("addCloumnNum"+addCloumnNum);
                                // console.log(that.cardList);
                                // console.log(cardsXYBak);
                                for (var i = 0; i < self.cardsXYBak.length; i++) {
                                    for (var j = 0; j < self.cardsXYBak[i].length; j++) {
                                        var tag = 0;
                                        if (self.cardsXYBak[i][j]) tag = self.cardsXYBak[i][j]['tag'];
                                        var card = nCards0.getChildByTag(tag);
                                        if (card && cc.sys.isObjectValid(card)) {
                                            card.stopAllActions();
                                            card.setRowColumn(j, i);
                                            card.newtag = (card.column + 1) * 100 + card.row + 1;
                                            var is4Same = self.cardsXYBak[i].length == 4 &&
                                                self.cardsXYBak[i][0].card == self.cardsXYBak[i][1].card &&
                                                self.cardsXYBak[i][0].card == self.cardsXYBak[i][2].card &&
                                                self.cardsXYBak[i][0].card == self.cardsXYBak[i][3].card &&
                                                self.cardsXYBak[i][0].card != 21;
                                            card.runAction(cc.sequence(
                                                cc.moveTo(0.1, cc.p(firstCardPos.x + (i) * (cardSize.w * cardScale - 2),
                                                    firstCardPos.y + (j) * (cardSize.h * cardScale - (is4Same ? 45 : 35)))),
                                                cc.callFunc(function (sender) {
                                                    sender.setTag(sender.newtag);
                                                    // console.log(sender.data + "===" + sender.column + "===" + sender.row + "===" + sender.getTag());
                                                    self.isBeginTouch = false;
                                                })
                                            ));
                                        }
                                    }
                                }
                                if (self.movecard && cc.sys.isObjectValid(self.movecard)) {
                                    self.movecard.setRowColumn(self.movetoxy.y, self.movetoxy.x + ((addCloumnNum == -1 && self.movexy.x < self.movetoxy.x) ? -1 : 0));
                                    self.movecard.setTag((self.movetoxy.x + 1 + ((addCloumnNum == -1 && self.movexy.x < self.movetoxy.x) ? -1 : 0)) * 100 + self.movetoxy.y + 1);
                                    //console.log(movecard.data+"==="+movecard.column+"==="+movecard.row+"==="+movecard.getTag());
                                    var addCloumnPosx = (self.movetoxy.add == 'false' && addCloumnNum == -1 && self.movexy.x < self.movetoxy.x) ? -1 : 0;
                                    self.movecard.stopAllActions();
                                    self.movecardTmp.setVisible(false);
                                    self.movecard.setPosition(self.movecardTmp.getPosition());
                                    self.movecard.setOpacity(255);

                                    if (self.movecard.getChildByName('tingmark') && cc.sys.isObjectValid(self.movecard.getChildByName('tingmark'))
                                        && self.movecard.getChildByName('tingmark').isVisible()) {
                                        self.movecardTmp.setTingMark(false);
                                        self.movecard.getChildByName('tingmark').setOpacity(255);
                                    }

                                    self.movecard.runAction(cc.sequence(
                                        cc.moveTo(0.1, cc.p(firstCardPos.x + (self.movetoxy.x + addCloumnPosx) * (cardSize.w * cardScale - 2),
                                            firstCardPos.y + (self.movetoxy.y) * (cardSize.h * cardScale - 35))),
                                        cc.callFunc(function (sender) {
                                            self.isBeginTouch = false;
                                        })
                                    ));
                                }
                            }

                            for (var i = 0; i < cardSprites.length; i++) {
                                var card = cardSprites[i];
                                card.setLocalZOrder(3 - card.row);
                            }


                            self.setSameCardShow(self.movecard.data, false);//选中相同颜色的
                            self.movecard = null;
                            self.positionBak = null;
                            self.movecard = null;
                            self.movexy = null;
                            self.movetoxy = null;
                            self.movetoxybak = null;

                            self.zipaiManager.CardList = deepCopy(cardList);
                            cc.sys.localStorage.setItem('Storage_handsCards', JSON.stringify(cardList));
                            self.setUpCardsHuXi();
                        }
                    } catch (e) {
                        network.sendPhz(5000, 'CheckHand/' + 'onTouchEnded' + '/movingError/' + e.toString());
                        showAlert('e : ' + e.toString());
                    }
                },
                onTouchCancel: function (touch, event) {
                    //console.log("cancel!!!!!!!!");
                    try {
                        if (self.movecard) {
                            self.setSameCardShow(self.movecard.data, false);//选中相同颜色的
                            self.movecardTmp.setVisible(false);
                            self.movecard.setPosition(self.movecardTmp.getPosition());
                            self.movecard.stopAllActions();
                            self.movecard.runAction(cc.sequence(
                                cc.moveTo(0.1, self.positionBak || cc.p(0, 0)),
                                cc.delayTime(0.4),
                                cc.callFunc(function () {
                                    self.movexy = null;
                                    self.movetoxy = null;
                                    self.movecard = null;
                                    self.movetoxybak = null;
                                    self.isMoving = false;
                                    self.isBeginTouch = false;
                                })
                            ));
                        }
                    } catch (e) {
                        network.sendPhz(5000, 'CheckHand/' + 'onTouchCancel' + '/movingError/' + e.toString());
                        showAlert('e : ' + e.toString());
                    }
                }
            });
            return cc.eventManager.addListener(chupaiListener, touchLayer);
        },
        networkStop: function () {
            if (this.zipaiManager.isReplay)
                return;
            network.stop();
        },
        playEffectByMap: function (card, sex) {
            playEffect('paohuzi_v' + card, sex);
        },
        playCPTPHEffect: function (cp, sex) {
            playEffect('paohuzi_v' + cp, sex);
        },
        playJSEffect: function (cp, sex) {
            playEffect('paohuzi_v' + cp, sex);
        },
        addOutCard: function (isCombo) {
            if (this.lastShowCard != null && this.lastShowCard[3] != true) { //不是亮张
                if (isCombo != true) {
                    var userPos = this.lastShowCard[1];
                    var card = this.lastShowCard[0];
                    var out = this.getOutNode(userPos);
                    out.addCard(card, true, this.showCard);
                }
                this.lastShowCard = null;
            }
        },
        moCard: function () {
            cc.log('moCard ==' + this.zipaiManager.LeftCardCount);
            this.game_zhang.setVisible(this.zipaiManager.LeftCardCount >= 0);
            if (this.zipaiManager.LeftCardCount > 0) {
                this.zipaiManager.LeftCardCount -= 1;
                this.txtCardCount.setString(this.zipaiManager.LeftCardCount);
            }
        },
        /**
         * 隐藏吃碰特效
         */
        hideImaAct: function () {
            this.imgAct.removeAllChildren();
            this.imgAct.setOpacity(0);
        },
        /**
         * 显示吃碰动画
         * @param typ
         * @param userPos
         */
        showActAnimation: function (typ, userPos) {
            var self = this;
            var animation_name = '';
            switch (typ) {
                case mCard.comboTypes.chi:
                    animation_name = 'chi';
                    break;
                case mCard.comboTypes.xiahuo:
                    animation_name = "xiahuo";
                    break;
                case mCard.comboTypes.chouwei:
                    animation_name = 'chouxiao';
                    break;
                case mCard.comboTypes.pao:
                    animation_name = 'pao';
                    break;
                case mCard.comboTypes.chongpao:
                    animation_name = 'chongpao';
                    break;
                case mCard.comboTypes.peng:
                    animation_name = 'peng';
                    break;
                case mCard.comboTypes.ti:
                    animation_name = 'qin';
                    break;
                case mCard.comboTypes.wei:
                    animation_name = 'xiao';
                    break;
                case mCard.comboTypes.wangdiao:
                    animation_name = 'wangdiao';
                    break;
                case mCard.comboTypes.wangchuang:
                    animation_name = 'wangchuang';
                    break;
                case mCard.comboTypes.wangzha:
                    animation_name = 'wangzha';
                    break;
                case mCard.comboTypes.hu:
                    animation_name = 'hu';
                    break;
            }
            if (animation_name == '') {
                return;
            }
            var playersNum = this.zipaiManager.PlayersNum;
            if (gameData.mapId == app.map_id.QYLDS || gameData.mapId == app.map_id.YZCHZ) {
                if (playersNum == 4) {
                    if (userPos == 0) {
                        this.imgAct.setPosition(DesignSize.width / 2, 400);
                    } else if (userPos == 1) {
                        this.imgAct.setPosition(DesignSize.width - 220, 270);
                    } else if (userPos == 2) {
                        this.imgAct.setPosition(DesignSize.width - 220, DesignSize.height - 170);
                    } else {
                        this.imgAct.setPosition(220, DesignSize.height - 170);
                    }
                }
                else if (playersNum == 3){
                    if (userPos == 0) {
                        this.imgAct.setPosition(DesignSize.width / 2, 400);
                    } else if (userPos == 1) {
                        this.imgAct.setPosition(DesignSize.width - 220, DesignSize.height - 170);
                    } else if (userPos == 2) {
                        this.imgAct.setPosition(220, DesignSize.height - 170);
                    } else {
                    }
                }
                else if (playersNum == 2){
                    if (userPos == 0) {
                        this.imgAct.setPosition(DesignSize.width / 2, 400);
                    } else if (userPos == 1) {
                        this.imgAct.setPosition(220, DesignSize.height - 170);
                    }
                }
            }
            else if (playersNum == 4) {
                if (userPos == 0) {
                    this.imgAct.setPosition(DesignSize.width / 2, 370);
                } else if (userPos == 1) {
                    this.imgAct.setPosition(DesignSize.width - 320, 250);
                } else if (userPos == 2) {
                    this.imgAct.setPosition(DesignSize.width - 320, 500);
                } else {
                    this.imgAct.setPosition(320, 500);
                }
            } else {
                if (userPos == 0) {
                    this.imgAct.setPosition(DesignSize.width / 2, 400);
                } else if (userPos == 1) {
                    this.imgAct.setPosition(DesignSize.width - 220, 550);
                } else {
                    this.imgAct.setPosition(220, 550);
                }
            }
            this.imgAct.removeAllChildren();
            this.imgAct.setOpacity(255);

            var spineAni = playSpine(zipai.res.sp_penghuzi_zi_json, animation_name, false, function () {
                setTimeout(function () {
                    self.imgAct.removeAllChildren();
                    self.imgAct.setOpacity(0);
                }, 100);
            });
            this.imgAct.addChild(spineAni);
            this.imgAct.setScale(1.5, 1.5);
        },
        showDefen: function (ScoreChange) {
            // if (ScoreChange && ScoreChange.length > 0) {
            //     var scoreList = ScoreChange.split('/');
            //     if (scoreList && scoreList.length == 8) {
            //         for (var i = 0; i < this.playersNum; i++) {
            //             var defenNum = scoreList[(this.pos0 + i) % 4 + 4];
            //             var zongfenNum = scoreList[(this.pos0 + i) % 4];
            //             this['txtHX' + i].setString('[得分:' + zongfenNum + ' ]');
            //             mRoom.InGameScore[i] = zongfenNum;
            //             if (defenNum && parseInt(defenNum) != 0) {
            //                 var row = i;
            //                 var head = $('node.info' + row + '.head' + row, this.playersInfo);
            //                 var defen = head.getChildByName('defen');
            //                 if (!defen) {
            //                     defen = new cc.LabelBMFont('', 'res/image/fonts/zongjiesuan_jifen_fnt.fnt');
            //                     defen.setName('defen');
            //                     defen.setScale(0.85);
            //                     defen.setPosition((row == 0 || row == 1) ? cc.p(50, 0) : cc.p(50, -20));
            //                     if (defenNum) defen.setString((parseInt(defenNum) > 0) ? '+' + defenNum : defenNum);
            //                     head.addChild(defen);
            //                 }
            //                 defen.stopAllActions();
            //                 defen.runAction(cc.sequence(
            //                     cc.moveBy(1, 0, 100).easing(cc.easeIn(1.5))
            //                     , cc.moveBy(1, 0, 50).easing(cc.easeOut(1.5))
            //                     , cc.fadeOut(1)
            //                     , cc.callFunc(function (sender) {
            //                         sender.removeFromParent();
            //                     })
            //                 ));
            //             }
            //         }
            //     }
            // }
        },
        removeCards: function (cardsToRemove, userPos, outCardColumn, outCardRow) {
            this.zipaiManager.removeCards(cardsToRemove, userPos, outCardColumn, outCardRow);
            if (userPos == 0) {
                this.setUpCards();
            } else {
                this.setUpOtherCards(userPos);
            }
        },
        /**
         * 检测牌数据信息
         */
        checkHandCardsPos: function () {
            var cardsList = this.getCardsNode(0).getChildren();
            var posArr = [];
            for (var i = 0; i < cardsList.length; i++) {
                var _cardSprite = cardsList[i];
                var pos = _cardSprite.getPosition();
                var x = pos.x;
                var y = pos.y;
                cc.log(pos);
            }
        },
        /**
         * 检验手牌
         * @param type
         * @param info
         */
        checkHandCards: function (type, info) {
            // return;
            if (type == 'movingError') {
                console.log('==========movingError=====================');
                network.sendPhz(5000, 'CheckHand/' + type + '/movingError/' + info);
                return;
            }
            //出牌检测牌是否重叠（位置相同） 和 牌是否有显隐的bug
            var cardsList = this.getCardsNode(0).getChildren();
            var posArr = [];
            var tag = [];
            for (var i = 0; i < cardsList.length; i++) {
                var _cardSprite = cardsList[i];
                if (_cardSprite.getName() == 'movecardTmp') {
                    continue;
                }
                var isBreak = false;
                var _data = '';
                var pos = _cardSprite.getPosition();

                for (var j = 0; j < posArr.length; j++) {
                    if (pos.x == posArr[j].x && pos.y == posArr[j].y) {
                        for (var m = 0; m < cardsList.length; m++) {
                            _data += (cardsList[m].data + ',');
                        }
                        network.sendPhz(5000, 'CheckHand/' + type + '/samePosition/' + _data);
                        // showMessageBox('有相同位置的牌出现了this.nCards0.length:' + cardsList.length + '  this.cardlistlen:' + this.cardList.length);
                        isBreak = true;
                        break;
                    }
                }
                if (isBreak) {
                    console.log('您手中的牌有重叠的了');
                    // showMessageBox('您手中的牌有重叠的了，请退出冲进！！！');
                    this.setUpCards();
                    break;
                }
                // tag.push(_cardSprite.getTag());
                posArr.push(pos);
            }


            for (var i = 0; i < cardsList.length; i++) {
                var _cardSprite = cardsList[i];
                if (cc.sys.isObjectValid(_cardSprite) && _cardSprite.getName() == 'movecardTmp') {
                    continue;
                }
                if (!_cardSprite.isVisible()) {
                    network.sendPhz(5000, 'CheckHand/' + type + '/cardVisible/false');
                    _cardSprite.setVisible(true);
                }
            }

        },
        /**
         * 移动牌结束
         * @param deleteCards
         * @param userPos
         */
        moveCardBack: function (deleteCards, userPos) {
            var self = this;
            console.log('=====正在移牌，先置回后在处理 removeCards');
            try {
                if (self.zorderBak) self.movecard.setLocalZOrder(self.zorderBak);
                self.movecardTmp.setVisible(false);
                self.movecard.stopAllActions();
                self.movecard.setPosition(self.movecardTmp.getPosition());
                self.movecard.setOpacity(255);
                self.movecard.runAction(cc.sequence(
                    cc.moveTo(0.1, self.positionBak),
                    cc.callFunc(function (sender) {
                        self.movexy = null;
                        self.movetoxy = null;
                        self.movetoxybak = null;
                        // cc.log('moveCardBack-----------callFunc');
                        self.movecard = null;
                        self.positionBak = null;
                        self.movetocardArr = [];
                        self.movetocardPosArr = [];
                        self.isMoving = false;
                        // that.isBeginTouch = false;
                        sender = null;
                    })
                ));
                setTimeout(function () {
                    self.movexy = null;
                    self.movetoxy = null;
                    self.movetoxybak = null;
                    // cc.log('moveCardBack-----setTimeout------callFunc');
                    self.movecard = null;
                    self.positionBak = null;
                    self.movetocardArr = [];
                    self.movetocardPosArr = [];
                    self.isMoving = false;
                }, 100);
                self.checkHandCards();
            } catch (e) {
                network.sendPhz(5000, 'moveCardBack/' + e.toString());
            }

            if (deleteCards) {
                this.removeCards(deleteCards, userPos);
            } else {
                self.scheduleOnce(function () {
                    self.setUpCards();
                }, .12);
                network.sendPhz(5000, 'moveCardBack/deleteCardsIsNull');
            }
        },
        /**
         * 显示牌
         * @param card
         * @param userPos
         * @param isMo
         * @param isLz
         */
        showCardAtPos: function (card, userPos, isMo, isLz, isWangfan) {
            if (isMo == undefined || isMo == null) isMo = false;
            if (card != 0 && !isLz) {
                if (isWangfan == undefined || isWangfan == false) {
                    this.playEffectByMap(card, gameData.sex);
                }
            }
            this.showNo = card;
            this.showCard.stopAllActions();
            this.showCard.setScale(1);
            this.showCard.setOpacity(255);
            this.showCard.setVisible(true);
            this.showCard.setData(this.showNo, null, 1);
            this.showCard.setMo(isMo);
            if (isLz) {
                mEffect.liangPai(this.showCard, userPos);
            } else {
                if (isMo) {
                    if (isWangfan == undefined || isWangfan == false) {
                        mEffect.moPai(this.showCard, userPos);
                    }
                    else {
                        var end_pos;
                        if (app.map_id.QYLDS == gameData.mapId || app.map_id.YZCHZ == gameData.mapId){
                            if (this.zipaiManager.PlayersNum == 4) {
                                if (userPos == 0) {
                                    end_pos = cc.p(DesignSize.width / 2, 450);
                                } else if (userPos == 1) {
                                    end_pos = cc.p(DesignSize.width - 440, 270);
                                } else if (userPos == 2) {
                                    end_pos = cc.p(DesignSize.width - 440, DesignSize.height - 215);
                                } else {
                                    end_pos = cc.p(440, DesignSize.height - 215);
                                }
                            }
                            if (this.zipaiManager.PlayersNum == 3) {
                                if (userPos == 0) {
                                    end_pos = cc.p(DesignSize.width / 2, 450);
                                } else if (userPos == 1) {
                                    end_pos = cc.p(DesignSize.width - 440, DesignSize.height - 215);
                                } else {
                                    end_pos = cc.p(440, DesignSize.height - 215);
                                }
                            }
                            if (this.zipaiManager.PlayersNum == 2) {
                                if (userPos == 0) {
                                    end_pos = cc.p(DesignSize.width / 2, 450);
                                } else {
                                    end_pos = cc.p(440, DesignSize.height - 215);
                                }
                            }
                        }
                        this.showCard.setPosition(end_pos);
                        this.showCard.setVisible(false);
                    }
                } else {
                    mEffect.chuPai(this.showCard, userPos);
                }
            }
            this.lastShowCard = [card, userPos, isMo, isLz];
        },
        /**
         * 显示亮张
         * @param card
         * @param userPos
         * @param isMo
         */
        showLZCardAtPos: function (card, userPos, isMo) {
            this.networkStop();
            this.scheduleOnce(function () {
                network.start();
            }, 1.5);
            this.showCardAtPos(card, userPos, isMo, true);
            this.scheduleOnce(function () {
                this.showCard.stopAllActions();
                this.showCard.setVisible(false);
                if (userPos == 0 && !this.zipaiManager.isReplay) {
                    if (mAction.isInOpenList(card) == false) {
                        //提过的亮张不要放进手牌  计算手里的牌数量
                        var cards = this.zipaiManager.CardList;
                        var comboList = mAction.combos[0];
                        var comboNum = 0;
                        for (var s = 0; s < comboList.length; s++) {
                            comboNum = comboNum + comboList[s].cards.length;
                        }
                        if (cards && (cards.length + comboNum) != 21) {
                            this.zipaiManager.addCard(card);
                            if (this.movecard && this.positionBak && (this.isBeginTouch)) {
                                this.moveCardBack();
                            } else {
                                this.setUpCards();
                            }
                        }
                    }
                }
            }, 1);
            if (this.zipaiManager.isReplay) {
                this.zipaiManager.showReplayLZCard(card, userPos);
                if (userPos == 0) {
                    this.setUpCards();
                } else {
                    this.setUpOtherCards(userPos);
                }
            }
        },
        /**
         * 展示相同的牌
         */
        setSameCardShow: function (showcard, isshow) {
            if (this.zipaiManager.isReplay) {
                return;
            }
            for (var i = 0; i < this.zipaiManager.PlayersNum; i++) {
                var open = this.getOpenNode(i);
                var openChileren = open.getChildren();
                for (var j = 0; j < openChileren.length; j++) {
                    var card = openChileren[j];
                    if (card.data == showcard && !card.isWei) {
                        card.setSelectCard(isshow);
                    }
                }
                var out = this.getOutNode(i);
                var outChileren = out.getChildren();
                for (var j = 0; j < outChileren.length; j++) {
                    var card = outChileren[j];
                    if (card.data == showcard) {
                        card.setSelectCard(isshow);
                    }
                }
            }
            if (this.isTurnOut && !this.isFreeze(showcard))
                this.tipLine.setVisible(isshow);
        },
        /**
         * 操作广播
         */
        setBroadCast: function () {
            var self = this;
            var broadCastData = this.zipaiManager.BroadCastData;
            if (!broadCastData || broadCastData.actStatus != 1) {
                return;
            }
            //{
            //action: action,
            //actList: actList,
            //userId: userId,
            //actStatus: actList[1],
            //actName: actList[2],
            //card: parseInt(actList[3]),
            //seq: parseInt(actList[4]),
            //info: actList.length > 5 ? actList[5] : '',
            //ScoreChange: data.ScoreChange,
            //userPos: userPos,
            //ismyself: (userPos == 0)
            //};
            self.showCDTime(-1);
            switch (broadCastData.actName) {
                case 'liangzhang':
                    self.showLZCardAtPos(broadCastData.card, broadCastData.userPos, true);
                    this.moCard();
                    break;
                case 'ShowCard':
                    self.networkStop();
                    self.scheduleOnce(function () {
                        network.start();
                    }, 0.5);
                    self.setSameCardShow(broadCastData.card, false);
                    self.showCardAtPos(broadCastData.card, broadCastData.userPos, false);
                    if (broadCastData.userPos == 0 || this.zipaiManager.isReplay) {
                        var deleteCards = [broadCastData.card];
                        self.removeCards(deleteCards, broadCastData.userPos, this.outCardColumn, this.outCardRow);
                        self.outCardColumn = null;
                        self.outCardRow = null;
                    }
                    if (broadCastData.card == 0) {
                        self.playEffectByMap(broadCastData.card.toString(), gameData.sex);
                    }
                    break;
                case 'mo':
                    self.networkStop();
                    self.addOutCard(false);
                    var action = null;
                    //解决回放时，当有提牌时棋牌区也出现所提的牌，导致出现5张相同的牌
                    if (self.zipaiManager.isReplay) {
                        action = cc.delayTime(0.3);
                    } else {
                        action = cc.delayTime(0.6);
                    }
                    this.runAction(cc.sequence(
                        action,
                        cc.callFunc(function () {
                            self.turnPos = broadCastData.userPos;
                            self.showCardAtPos(broadCastData.card, broadCastData.userPos, true);
                            self.moCard();
                        }),
                        settingData.jisuchupai ? cc.delayTime(0.0) : cc.delayTime(0.3),
                        cc.callFunc(function () {
                            network.start();
                        })
                    ));
                    break;
                case 'bakuai':
                    self.addOutCard(false);
                    self.moCard();
                    if (broadCastData.userPos == 0) {
                        self.zipaiManager.addCard(broadCastData.card);
                    }
                    break;
                case 'peng':
                    self.addOutCard(true);
                    var cardList = [broadCastData.card, broadCastData.card, broadCastData.card];
                    var open = self.getOpenNode(broadCastData.userPos);//['open' + userPos];
                    open.addCards(cardList, mCard.comboTypes.peng);
                    mEffect.chiPai(open, broadCastData.userPos);
                    self.setUpHX(broadCastData.userPos);
                    self.showCard.setVisible(false);

                    self.showActAnimation(mCard.comboTypes.peng, broadCastData.userPos);
                    if (broadCastData.userPos == 0 || self.zipaiManager.isReplay) {
                        var deleteCards = [broadCastData.card, broadCastData.card, broadCastData.card];
                        self.removeCards(deleteCards, broadCastData.userPos);
                    }
                    self.playCPTPHEffect('peng', gameData.sex);
                    //攸县玩法  显示得分
                    //self.showDefen(broadCastData.ScoreChange);
                    break;
                case 'chi':
                    self.addOutCard(true);
                    self.nChiList.removeAllChildren();
                    var cardList = broadCastData.info.split(',');
                    var open = self.getOpenNode(broadCastData.userPos);
                    var count = cardList.length / 3;
                    for (var i = 0; i < count; i++) {
                        var combo = [];
                        var index = i * 3;
                        combo.push(cardList[index]);
                        combo.push(cardList[index + 1]);
                        combo.push(cardList[index + 2]);

                        var comboTyp = mCard.getComboType(combo);
                        // open.addCards(combo, comboTyp);
                        //吃的第几张牌需要特殊现实   王常春 2016-7-8 add
                        //吃的放在第一个位置
                        for (var x = 0; x < combo.length; x++) {
                            if (parseInt(broadCastData.card) == parseInt(combo[x])) {
                                var tmp = combo[x];
                                for (var y = x + 1; y < 3; y++) {
                                    combo[y - 1] = combo[y];
                                }
                                combo[2] = tmp;
                            }
                        }
                        open.addCards(combo, comboTyp, false);
                    }
                    cc.log('open = ' + open);
                    cc.log('userPos = ' + broadCastData.userPos);
                    mEffect.chiPai(open, broadCastData.userPos);
                    self.setUpHX(broadCastData.userPos);
                    self.showCard.setVisible(false);

                    self.showActAnimation(mCard.comboTypes.chi, broadCastData.userPos);
                    if (broadCastData.userPos == 0 || self.zipaiManager.isReplay) {
                        var removeCards = mCard.copyCards(cardList);
                        for (var i = 0; i < removeCards.length; i++) {
                            if (removeCards[i] == broadCastData.card) {
                                removeCards.splice(i, 1);
                                break;
                            }
                        }
                        self.removeCards(removeCards, broadCastData.userPos);
                    }
                    if (count > 1) {
                        self.playCPTPHEffect('bi', gameData.sex);
                    } else {
                        self.playCPTPHEffect('chi', gameData.sex);
                    }
                    break;
                case 'ti':
                    self.networkStop();
                    self.scheduleOnce(function () {
                        network.start();
                    }, 0.5);

                    self.addOutCard(true);
                    var cardList = [broadCastData.card, broadCastData.card, broadCastData.card, broadCastData.card];
                    var isOpen = false;
                    //info == true牌桌上的偎
                    if (broadCastData.info == 'true') {
                        isOpen = true;
                    }
                    var open = self.getOpenNode(broadCastData.userPos);//['open' + userPos];
                    open.addCards(cardList, mCard.comboTypes.ti, isOpen);
                    mEffect.chiPai(open, broadCastData.userPos, true);
                    self.setUpHX(broadCastData.userPos);
                    self.showCard.setVisible(false);//add hide

                    self.showActAnimation(mCard.comboTypes.ti, broadCastData.userPos);
                    if ((broadCastData.userPos == 0 && isOpen == false) || self.zipaiManager.isReplay) {
                        self.isBeginTouch = true;
                        var deleteCards = [broadCastData.card, broadCastData.card, broadCastData.card, broadCastData.card];
                        // cc.log("ti-----------1");
                        if (self.movecard && cc.sys.isObjectValid(self.movecard) && self.positionBak && (self.isBeginTouch)) {
                            // cc.log("ti-----------2");
                            self.moveCardBack(deleteCards, broadCastData.userPos);
                        } else {
                            self.removeCards(deleteCards, broadCastData.userPos);
                        }
                    }

                    this.playCPTPHEffect('ti', gameData.sex);
                    //攸县玩法  显示得分
                    //this.showDefen(broadCastData.ScoreChange);
                    break;
                case 'pao':
                    self.addOutCard(true);
                    self.networkStop();
                    self.scheduleOnce(function () {
                        network.start();
                    }, 0.5);
                    var cardList = [broadCastData.card, broadCastData.card, broadCastData.card, broadCastData.card];
                    var isOpen = false;
                    if (broadCastData.info == 'true') {
                        isOpen = true;
                    }
                    var open = self.getOpenNode(broadCastData.userPos);
                    open.addCards(cardList, mCard.comboTypes.pao, isOpen);
                    mEffect.chiPai(open, broadCastData.userPos);
                    self.setUpHX(broadCastData.userPos);
                    self.showCard.setVisible(false);

                    self.showActAnimation(mCard.comboTypes.pao, broadCastData.userPos);
                    if ((broadCastData.userPos == 0 && isOpen == false) || self.zipaiManager.isReplay) {
                        self.isBeginTouch = true;
                        var deleteCards = [broadCastData.card, broadCastData.card, broadCastData.card];
                        // cc.log("pao-----------1");
                        if (self.movecard && cc.sys.isObjectValid(self.movecard) && self.positionBak && (self.isBeginTouch)) {
                            // cc.log("pao-----------2");
                            self.moveCardBack(deleteCards, broadCastData.userPos);
                        } else {
                            self.removeCards(deleteCards, broadCastData.userPos);
                        }
                    }
                    this.playCPTPHEffect('pao', gameData.sex);
                    //攸县玩法  显示得分
                    //this.showDefen(broadCastData.ScoreChange);
                    break;
                case 'wei':
                    self.networkStop();
                    self.scheduleOnce(function () {
                        network.start();
                    }, 0.5);
                    self.showCard.setVisible(true);
                    this.scheduleOnce(function () {
                        self.showCard.setVisible(false);
                    }, .25);
                    self.addOutCard(true);
                    var cardList = [broadCastData.card, broadCastData.card, broadCastData.card];
                    var open = self.getOpenNode(broadCastData.userPos);
                    open.addCards(cardList, mCard.comboTypes.wei, false);
                    mEffect.chiPai(open, broadCastData.userPos, true);
                    self.setUpHX(broadCastData.userPos);
                    self.showCard.setVisible(false);//add hide

                    self.showActAnimation(mCard.comboTypes.wei, broadCastData.userPos);
                    if (broadCastData.userPos == 0 || self.zipaiManager.isReplay) {
                        self.isBeginTouch = true;
                        var deleteCards = [broadCastData.card, broadCastData.card, broadCastData.card];
                        if (self.movecard && cc.sys.isObjectValid(self.movecard) && self.positionBak && (self.isBeginTouch)) {
                            self.moveCardBack(deleteCards, broadCastData.userPos);
                        } else {
                            self.removeCards(deleteCards, broadCastData.userPos);
                        }
                    }
                    this.playCPTPHEffect('wei', gameData.sex);
                    //攸县玩法  显示得分
                    //this.showDefen(broadCastData.ScoreChange);
                    break;
                case 'chouwei':
                    self.networkStop();
                    self.scheduleOnce(function () {
                        network.start();
                    }, 0.5);

                    self.addOutCard(true);
                    var cardList = [broadCastData.card, broadCastData.card, broadCastData.card];
                    var open = self.getOpenNode(broadCastData.userPos);
                    open.addCards(cardList, mCard.comboTypes.chouwei, false);
                    mEffect.chiPai(open, broadCastData.userPos, true);
                    self.setUpHX(broadCastData.userPos);
                    self.showCard.setVisible(false);//add hide

                    self.showActAnimation(mCard.comboTypes.chouwei, broadCastData.userPos);
                    if (broadCastData.userPos == 0 || self.zipaiManager.isReplay) {
                        self.isBeginTouch = true;
                        var deleteCards = [broadCastData.card, broadCastData.card, broadCastData.card];
                        if (self.movecard && cc.sys.isObjectValid(self.movecard) && self.positionBak && (self.isBeginTouch)) {
                            self.moveCardBack(deleteCards, broadCastData.userPos);
                        } else {
                            self.removeCards(deleteCards, broadCastData.userPos);
                        }
                    }
                    // if (mRoom.wanfatype == mRoom.GUILIN) {
                    //     self.playCPTPHEffect('chouwei', gameData.sex);
                    // } else {
                    //     self.playCPTPHEffect('wei', gameData.sex);
                    // }
                    self.playCPTPHEffect('wei', gameData.sex);
                    //攸县玩法  显示得分
                    //self.showDefen(broadCastData.ScoreChange);
                    break;
                case 'hu':
                    if (broadCastData.info != null && broadCastData.info.length > 0) {
                        ZiPaiRoomData.gameOverHuInfo = JSON.parse(broadCastData.info);
                    }
                    this.showActAnimation(mCard.comboTypes.hu, broadCastData.userPos);
                    break;
                default :
                    break;
            }
        },
        userAct: function (act, card, target, info) {
            var actString = mAction.getActionString(act);
            if (info != null) {
                info = '/' + info;
            } else {
                info = '';
            }
            if (actString == 'none') {
                actString = 'guo';
            }
            network.sendPhz(5000, 'EatCard/' + actString + '/' + card + '/' + this.inSeq + info);
            this.setTurnInOver();
        },
        setTurnInOver: function () {
            var that = this;
            if(!cc.sys.isObjectValid(that.nAction)){
                return ;
            }
            that.nAction.runAction(
                cc.sequence(
                    cc.scaleTo(0.1, 0, 0),
                    cc.callFunc(function () {
                        cc.log('setTurnInOver');
                        that.nAction.setScale(1);
                        that.nAction.setVisible(false);
                        for (var i = 0; i < that.listActBtn.length; i++) {
                            that.listActBtn[i].setVisible(false);
                        }
                    })
                )
            );
            var _ChiBiWindow = window.curScene.getChildByName('ZiPai_ChiBiWindow');
            if (_ChiBiWindow) {
                _ChiBiWindow.removeFromParent(true);
            }
            that.nChiList.removeAllChildren();
            that.secondsLeft = 0;
            that.isTurnIn = false;
        },
        /**
         * 显示吃、碰、过、胡 按钮
         */
        showActions: function (actList) {
            this.nAction.setVisible(true);
            var btnList = [];
            for (var i = 0; i < actList.length; i++) {
                var act = actList[i];
                if (act == PENG) {
                    btnList.push(this.listActBtn[2]);
                }
                if (act == CHI) {
                    btnList.push(this.listActBtn[1]);
                }
                if (act == HU) {
                    btnList.push(this.listActBtn[0]);
                }
                if (act == DENGHU) {
                    btnList.push(this.listActBtn[4]);
                }
                if (act == GUO) {
                    btnList.push(this.listActBtn[3]);
                }
            }
            for (var i = 0; i < btnList.length; i++) {
                var bt = btnList[i];
                bt.setPositionX(i * -200 - 100);
                bt.setVisible(true);
            }
        },
        /**
         * 选择吃界面
         */
        showChiSelect: function () {
            var self = this;
            this.chiArray = this.zipaiManager.getChiArray();
            this.nChiList.removeAllChildren();
            if (this.chiArray == null) return;
            if (this.zipaiManager.QuickChi && this.chiArray.length == 1 && this.chiArray[0].length == 3) {
                this.userAct(CHI, this.showNo, false, this.chiArray[0]);
            } else {
                var _ChiBiWindow = window.curScene.getChildByName('ZiPai_ChiBiWindow');
                if (!_ChiBiWindow) {
                    showWindow('ZiPai_ChiBiWindow', this.chiArray, this.showNo, this);
                } else {
                    _ChiBiWindow.setVisible(!_ChiBiWindow.isVisible());
                }
            }
        },
        /**
         * 操作吃、碰、过、胡 按钮
         */
        onActionBtn: function (tag, target) {
            var self = this;
            if (self.isBeginTouch && self.movecard && self.positionBak) {
                if (self.zorderBak) self.movecard.setLocalZOrder(self.zorderBak);
                self.movecardTmp.setVisible(false);
                self.movecard.stopAllActions();
                self.movecard.setPosition(self.movecardTmp.getPosition());
                self.movecard.setOpacity(255);
                self.movecard.runAction(cc.sequence(
                    cc.moveTo(0.1, self.positionBak),
                    cc.callFunc(function (sender) {
                        self.movexy = null;
                        self.movetoxy = null;
                        self.movetoxybak = null;
                        self.movecard = null;
                        self.positionBak = null;
                        self.isMoving = false;
                        self.isBeginTouch = false;
                        sender = null;
                        // cc.log("----------onActionBtn  callFunc ");
                    })
                ));
                return;
            }

            var hubtn = self.$('bt1', this.nAction);
            if (tag == 2) {
                if (hubtn.isVisible() == true) {
                    showMessageBox('当前可以胡牌，请问是否选择吃?', function () {
                        self.showChiSelect();
                    });
                } else {
                    self.showChiSelect();
                }
            } else if (tag == 3) {
                if (hubtn.isVisible() == true) {
                    showMessageBox('当前可以胡牌，请问是否选择碰?', function () {
                        self.userAct(PENG, self.showNo, target);
                    });
                } else {
                    self.userAct(PENG, self.showNo, target);
                }
            } else if (tag == 1) {
                var AcCards = self.zipaiManager.AcCards;
                if (AcCards && AcCards['Cards'] && AcCards['Cards'].length > 0) {
                    if (AcCards['Cards'].length > 1) {
                        showWindow('ZiPai_HuWindow', AcCards['Cards'], self.showNo, this);
                        self.nAction.setVisible(false);
                    } else {
                        var huPaiDate = AcCards['Cards'][0];
                        var flag = huPaiDate['Type'];
                        var denghu = ((flag & DENGHU) > 0) ? true : false;
                        if (denghu) {
                            self.userAct(HUDENGHU, huPaiDate['Cards'], target);
                        } else {
                            self.userAct(HU, huPaiDate['Cards'], target);
                        }
                    }
                } else {
                    self.userAct(HU, self.showNo, target);
                }
            } else if (tag == 4) {
                //过得时候判断一下  有没有 胡的选项,有的话,提示
                if (hubtn.isVisible() == true) {
                    showMessageBox('当前可以胡牌，请问是否选择过?', function () {
                        self.userAct(GUO, self.showNo, target);
                    });
                } else {
                    self.userAct(GUO, self.showNo, target);
                }
            } else if (tag == 5) {
                if (hubtn.isVisible() == true) {
                    showMessageBox('当前可以胡牌，请问是否选择等胡?', function () {
                        self.userAct(DENGHU, self.showNo, target);
                    });
                } else {
                    self.userAct(DENGHU, self.showNo, target);
                }
            }
            Filter.remove(target);
        },
        /**
         * 是否进牌
         */
        setTurnIn: function () {
            var card = this.zipaiManager.TurnInCard;
            var flag = this.zipaiManager.Flag;
            var remark = this.zipaiManager.Remark;
            var seq = this.zipaiManager.TurnInSeq;
            this.nChiList.removeAllChildren();
            this.isTurnOut = false;
            this.isTurnIn = true;
            this.inSeq = seq;
            this.secondsLeft = 25;

            this.turnInData = {};
            this.turnInData.Card = card;
            this.turnInData.Flag = flag;

            //只有一个过
            if (flag == GUO) {
                return;
            }
            var chi = ((flag & CHI) > 0) ? true : false;
            var peng = ((flag & PENG) > 0) ? true : false;
            var hu = ((flag & HU) > 0) ? true : false;
            var guo = ((flag & GUO) > 0) ? true : false;
            var pao = ((flag & PAO) > 0) ? true : false;
            var ti = ((flag & TI) > 0) ? true : false;
            var wei = ((flag & WEI) > 0) ? true : false;
            var chouwei = ((flag & CHOUWEI) > 0) ? true : false;
            var tianhu = ((flag & TIANHU) > 0) ? true : false;//TIANHU
            var denghu = ((flag & DENGHU) > 0) ? true : false;
            var actList = [];
            if (tianhu == true) {
                this.userAct(HU, this.showNo);
            } else if (pao == true) {
                this.userAct(PAO, card);
            } else if (ti == true) {
                this.userAct(TI, card);
            } else if (wei == true) {
                this.userAct(WEI, card);
            } else {
                if (guo == true) actList.push(GUO);
                if (denghu == true) actList.push(DENGHU);
                if (chi == true) actList.push(CHI);
                if (peng == true) actList.push(PENG);
                if (hu == true) actList.push(HU);
                this.showActions(actList);
            }
        },
        /**
         * 设置玩家指向
         */
        setTurnOutArrow: function () {
            var self = this;
            // var arrow_tou = self.$('arrow_tou', self.cd);
            // if (!arrow_tou) {
            //     return;
            // }
            // var rotate = [0, -135, 135];
            // var toupos = [cc.p(45, -20), cc.p(90, 100), cc.p(0, 100)];
            // if (self.playersNum == 4) {
            //     rotate = [0, -45, -135, 135];
            //     toupos = [cc.p(45, -20), cc.p(100, -20), cc.p(100, 100), cc.p(-20, 100)];
            //     arrow_tou.setRotation(rotate[self.turnPos] || 0);
            //     arrow_tou.setPosition(toupos[self.turnPos]);
            // } else {
            //     arrow_tou.setRotation(rotate[self.turnPos] || 0);
            //     arrow_tou.setPosition(toupos[self.turnPos]);
            // }

            //cd 中显示光圈
            // if (this.zipaiManager.isGameStart == true) {
            //     for (var i = 0; i < self.zipaiManager.PlayersNum; i++) {
            //         var infoNode = self.$('info' + i, self.PlayerInfoNode);
            //         var guangquan = infoNode.getChildByName('head').getChildByName('guangquan');
            //         guangquan.setVisible((i == self.turnPos) ? true : false);
            //     }
            // }
            this.countDown(self.turnPos);
        },
        /**
         * 设置出牌对象
         */
        setTurnOut: function () {
            var userId = this.zipaiManager.Turn;
            var seconds = this.zipaiManager.Second;
            var TurnOutSeq = this.zipaiManager.TurnOutSeq;
            var Freeze = this.zipaiManager.Freeze;
            var Notice = this.zipaiManager.Notice;
            var turnPos = this.zipaiManager.g_uid_to_pos[userId];

            this.setTurnInOver();
            this.showCard.stopAllActions();
            this.showCard.setVisible(false);
            this.nChiList.removeAllChildren();
            this.turnPos = turnPos;
            this.secondsLeft = 25;
            this.bigAction = null;
            this.setTurnOutArrow();

            if (turnPos == 0) {
                this.isTurnOut = true;
                this.isTurnIn = false;
                this.outSeq = TurnOutSeq;
                var cards = this.zipaiManager.SeverCardList;
                if (cards.length == 0) {
                    this.userShowCard(0, true);
                }
            }
            //冻结 Freeze
            if (userId == gameData.uid && Freeze && Freeze.length > 0) this.setFreezeCard(Freeze);
            //提示的牌 Notice

            if (userId == gameData.uid && Notice && Notice.length > 0) {
                this.Notice = Notice;
            } else {
                this.Notice = null;
            }
        },
        isFreeze:function (freezeCard) {
            if(this.Freeze){
                for (var i = 0; i < this.Freeze.length; i++) {
                    if (this.Freeze[i] == freezeCard) {
                        return true;
                    }
                }
            }
            return false;
        },
        setFreezeCard: function (Freeze) {
            this.Freeze = Freeze || this.zipaiManager.g_uid_to_Freeze[gameData.uid];
            if (this.Freeze) {
                var cardList = this.getCardsNode(0).getChildren();
                for (var i = 0; i < cardList.length; i++) {
                    var card = cardList[i];
                    card.setGrayCard(this.isFreeze(card.data));
                }
            }
        },
        /**
         * 游戏结算
         */
        setGameOver: function () {
            this.showCard.stopAllActions();
            this.showCard.setVisible(false);
            var gameOverData = this.zipaiManager.gameOverData;
            if (!gameOverData) {
                return;
            }
            if (ZiPaiRoomData.gameOverHuInfo == null) {
                playEffect('huangz');//胡不得
            } else {
                // if (gameOverData['WinnerZimo']) {
                //     this.playCPTPHEffect('zimo', gameData.sex);//自摸
                // } else {
                this.playCPTPHEffect('hu', gameData.sex);
                // }
            }
            this.setTurnInOver();
            this.showOtherPai();
            if (gameOverData['XingCard']) {
                this.scheduleOnce(this.showFanXingAni.bind(this), 0.3);
                this.scheduleOnce(this.showGameResult.bind(this), 1.35);
            } else {
                this.scheduleOnce(this.showGameResult.bind(this), .8);
            }
        },
        showOtherPai: function () {
            if (this.zipaiManager.isReplay) {
                return;
            }
            var gameOverData = this.zipaiManager.gameOverData;
            if (!gameOverData) {
                return;
            }
            var Users = gameOverData['Users'];
            for (var i = 0; i < Users.length; i++) {
                var infoData = Users[i];
                var uid = infoData['UserID'];
                var row = this.zipaiManager.g_uid_to_pos[uid];
                this.updateScore(row);
                if (uid != gameData.uid) {
                    this.setUpOtherCards(row);
                    this.getOpenNode(row).setWeiColor(row);
                } else {

                }
            }
            if (this.playersNum == 2 && this.zipaiManager.Sipai && gameOverData.Sipai) {
                this.setUpOtherCards(2);
                this.getOpenNode(2).setVisible(false);
            }
        },
        /**
         * 翻醒动画
         */
        showFanXingAni: function () {
            var gameOverData = this.zipaiManager.gameOverData;
            this.nLaizi.removeAllChildren();
            var card = new Card();
            this.nLaizi.addChild(card);
            card.setPositionY(this.nLaizi.getPositionY());
            card.setPositionX(90);
            card.setData(gameOverData['XingCard'], this.nLaizi, 2);
            if (gameOverData['XingCard'] == 0) {
                card.setVisible(false);
                this.nLaizi.setVisible(false);
            } else {
                this.nLaizi.setVisible(true);
                card.setVisible(true);
                var sscname = (this.zipaiManager.Fanxing == 'gen') ? res.Phz_genxingAni : res.Phz_fanxingAni;
                var ccsScene = ccs.load(sscname, getCCSFileNamePath(sscname));
                var fanxingAni = ccsScene.node;
                fanxingAni.setName('fingerAnimation');
                fanxingAni.setPosition(cc.p(1280 / 2, 720 / 2 + 150));
                fanxingAni.setPositionX(cc.winSize.width / 2);
                this.addChild(fanxingAni, 100);
                fanxingAni.setScale(.8);
                fanxingAni.runAction(ccsScene.action);
                ccsScene.action.play('action', true);
                this.scheduleOnce(function () {
                    fanxingAni.removeFromParent();
                }, 1);

                this.scheduleOnce(function () {
                    var showfancard = new Card();
                    showfancard.setScale(.6);
                    showfancard.setData(gameOverData['XingCard'], this, 1);
                    showfancard.setPosition(cc.p(1280 / 2, 720 / 2 + showfancard.getContentSize().height / 2 + 140));
                    showfancard.setPositionX(cc.winSize.width / 2);
                    this.addChild(showfancard, 101);
                    showfancard.runAction(cc.sequence(
                        cc.scaleTo(0.25, -.6, .6)
                        , cc.scaleTo(0.30, .6, .6)
                        , cc.scaleTo(0.40, .8, .8)
                        , cc.removeSelf()
                    ));
                }, 0.1);
            }
        },
        showGameResult: function (isPlayMusic) {
            cc.sys.localStorage.setItem('Storage_handsCards', []);
            if (gameData.mapId == app.map_id.QYLDS || gameData.mapId == app.map_id.YZCHZ) {
                showWindow('ZiPai_JieSuanWindow_qylds', this.zipaiManager.gameOverData, this);
            }
            else {
                showWindow('ZiPai_JieSuanWindow', this.zipaiManager.gameOverData, this);
            }
            if (isPlayMusic) {
                playEffect('getw');
            }
            this.panelResult.setVisible(!this.zipaiManager.isReplay);
        },
        /**
         * 总结算
         */
        showRoomClean: function () {
            var RoomResultDate = this.zipaiManager.RoomResultDate;
            if (!RoomResultDate) return;
            showWindow('ZiPai_ZongJieSuanWindow', RoomResultDate, RoomResultDate['ClubID']);
            this.zipaiManager.RoomResultDate = null;
            var cardsNode = self.$('PlayerInfo.node_wang');
            if(cardsNode){
                cardsNode.removeAllChildren();
            }
        },
        getOriginalPos: function () {
            return 0;
        },
        /**
         * 获取表情坐标
         * @param caster
         * @param patient
         * @param isNotMid
         * @returns {{}}
         */
        getEffectEmojiPos: function (caster, patient, isNotMid) {
            var self = this;
            var pos = {};
            var infoCaster = self.$('info' + caster, self.PlayerInfoNode);
            pos[caster] = infoCaster ?
                infoCaster.convertToWorldSpace(self.$('head', infoCaster).getPosition()) : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
            var infoPatient = self.$('info' + patient, self.PlayerInfoNode);
            pos[patient] = (patient != self.getOriginalPos() &&
            infoPatient) || isNotMid ?
                infoPatient.convertToWorldSpace(self.$('head', infoPatient).getPosition()) : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
            return pos;
        },
        /**
         * 获取自己的ChatInfo节点
         */
        getChatInfoNode: function (_idx) {
            var self = this;
            var ChatInfoNode = self.$('info' + _idx + '.ChatInfo', self.PlayerInfoNode);
            return ChatInfoNode;
        },
        /**
         * 获取玩家坐标
         * @param uid
         */
        getRowByUid: function (uid) {
            return this.zipaiManager.g_uid_to_pos[uid];
        },
        /**
         * 回放相关
         */
        beginReplay: function () {
            this.clearRoom();
            this.setUpPlayers();
        },
        /**
         * 录像回放  小手点击
         */
        showReplayAction: function (action) {
            var self = this;
            if (!self.PlayerInfoNode) {
                return;
            }
            var actionData = action.split('/');
            var userId = actionData[0];
            var mainAction = actionData[1];
            var subAction = actionData[2];
            var replay_act = null;
            if (subAction == 'chi' || subAction == 'peng' || subAction == 'hu' || subAction == 'guo') {
                var pos = self.zipaiManager.g_uid_to_pos[userId];
                replay_act = self.$('replay_act' + pos, self.PlayerInfoNode);
                if (!!replay_act) {
                    replay_act.setVisible(true);
                    var bt = self.$(subAction, replay_act);
                    this.playHand(bt);
                }
            }
        },
        playHand: function (bt) {
            cc.spriteFrameCache.addSpriteFrames(zipai.res.hand_plist);
            var animFrames = [cc.spriteFrameCache.getSpriteFrame('hand0.png'), cc.spriteFrameCache.getSpriteFrame('hand1.png')];
            var animation = new cc.Animation(animFrames, 0.2);
            var action = cc.animate(animation);
            var sprite = new cc.Sprite(animFrames[0]);
            sprite.x = 40;
            sprite.y = 20;
            bt.addChild(sprite);
            sprite.runAction(action);
        },
        hideReplayAction: function () {
            var self = this;
            if (!self.PlayerInfoNode) {
                return;
            }
            for (var i = 0; i < 4; i++) {
                var replay_act = self.$('replay_act' + i, self.PlayerInfoNode);
                if (replay_act) {
                    self.$('replay_act' + i + '.chi', self.PlayerInfoNode).removeAllChildren();
                    self.$('replay_act' + i + '.peng', self.PlayerInfoNode).removeAllChildren();
                    self.$('replay_act' + i + '.hu', self.PlayerInfoNode).removeAllChildren();
                    self.$('replay_act' + i + '.guo', self.PlayerInfoNode).removeAllChildren();
                    replay_act.setVisible(false);
                }
            }
        },
    });
})(window);